how to handle the error in dojo - javascript

This is a piece of an existing dojo based project
nps.makeRequest = function(args) {
//add some default params
return dojo.xhr("POST", args, true); // dojo/_base/Deferred
};
The issue is if the respose has an error message(text message) it is displayed properly.
if the response is say 404 and if there is a custom error page served , it will display the HTML source code of 404 page instead of interpreting it.
how to handle the error here?

You can either do
args = {
url: 'http://...',
error: function() { /* this handles error*/ }
};
nps.makeRequest(args);
Or you can use the deferred:
nps.makeRequest({url: 'foo'}).then(function() { /* this handles happy flow*/ }, function() { /* this handles error*/ });

Related

SAPUI5 mock server doesn't receive requests

I didn't find a solution for this problem. I'm currently working with the CRUD Master-Detail Application WebIDE template and added some custom functions with OData calls. When running the app with mock server it loads the mock data. So far so good. But if I send a read request to the mock server it throws a 404 not found error.
Request URL
https://webidetesting[...].dispatcher.hana.ondemand.com/here/goes/your/serviceurl/MyEntity(12345)
Here's the mock server part in my index file flpSandboxMockServer.html:
<script>
sap.ui.getCore().attachInit(function() {
sap.ui.require([
"my/project/localService/mockserver"
], function (mockserver) {
// set up test service for local testing
mockserver.init();
// initialize the ushell sandbox component
sap.ushell.Container.createRenderer().placeAt("content");
});
});
</script>
The OData read call looks like:
onRemoveMyEntityBtnPress: function () {
let oEntityTable = this.byId("lineItemsList");
let aSelectedItems = oEntityTable.getSelectedItems();
let oModel = this.getModel();
for (let oSelectedItem of aSelectedItems) {
let sBindingPath = oSelectedItem.getBindingContext().getPath();
let sGuid = this._selectGuidFromPath(sBindingPath);
this._loadEntityFromService(sGuid, oModel).then((oData) => {
// Next step: change a property value
}).catch((oError) => {
jQuery.sap.log.error(oError);
});
}
if (oModel.hasPendingChanges()) {
oModel.submitChanges();
}
},
_loadEntityFromService: function (sGuid, oModel) {
return new Promise((resolve, reject) => {
oModel.read(`/MyEntity(${sGuid})`, {
success: (oData) => {
resolve(oData);
},
error: (oError) => { // call always ends up here with 404 error
reject(oError);
}
});
});
},
Does someone have an idea what I else have to do to send my read request to the mock service?
Finally found the solution!
I used the OData entity type to read my entity. I changed the destination to my entity set and now it doesn't throw a 404 error.

Rendering reCaptcha V2.0 widget within Marionette Itemview

This will be a post where I ask the question and propose a solution
Since having had several trouble and having looked around a lot I decided to post my final solution for anyone else to take profit from it.
Question:
How to render google's reCaptcha v2.0 widget and verifying it in a Marionettejs app with a java back end.
After the common steps and following google guides to render the re captcha my captcha still didn't render, so here comes my solution:
Rendering the captcha and the inclusion of the script are both made inside the itemview onRender function:
'text!login/templates/form.html',
'app'
], function (app, Marionette, Backbone, _, $, Handlebars, FormTemplate) {
return Marionette.ItemView.extend({
template: Handlebars.compile(FormTemplate),
ui: {
form: '
},
events: {
'submit #ui.form': 'onSubmit'
},
onRender: function() {
this.loadCaptcha();
},
loadCaptcha: function() {
var self = this;
var getRecaptchaResponse = function(response) {
self.captchaResponse = response;
};
window.renderCaptcha = function () {
self.captchaWidgetId = grecaptcha.render('yourCaptchaDiv', {
sitekey: 'YourSiteKey',
callback: getRecaptchaResponse
});
};
$.getScript('https://www.google.com/recaptcha/api.js?onload=renderCaptcha&render=explicit', function() {});
},
...
}
I tried other ways of loading the script with several errors, like the script loaded before the div for it, or the browser says de Dom has completely loaded but the onRender gets called after
I had to include a div for the captcha widget to load in, this is in
form.html
<div id="reCaptcha" class="btn"></div>
That will have your widget rendered, now you need to both verify it has been filled and it is a valid user response with google, for this I use the same module and use the next function:
onSubmit: function (e) {
//only act if the captcha has been filled - This could be easily erased from a browser, but a back end verification takes place too
if (grecaptcha.getResponse() !== "") {
e.preventDefault();
var _view = this;
this.blockForm();
$.ajax({
url: 'yourLoginService',
type: 'POST',
data: {
userLogin: this.ui.user.val(),
userPassword: this.ui.password.val(),
//get the captcha response
captchaResponse: grecaptcha.getResponse()
}
}).done(function (data) {
app.router.navigate('', {trigger: true});
_view.destroy();
}).fail(function (jqXHR, textStatus, errorThrown) {
// your fail handling
});
}
},
Then comes the time to verify your captcha server side using the secret key provided by google (note this is a Java6 app, therefore the clumbersome exception Handling):
//some other imports ignored
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
class Captcha {
private static final String CAPTCHA_SECRET_KEY = "YourSecretKey";
private static final Logger LOGGER = Logger.getLogger(Captcha.class);
static boolean isCaptchaValid(String response) {
try {
String url = "https://www.google.com/recaptcha/api/siteverify?"
+ "secret=" + CAPTCHA_SECRET_KEY
+ "&response=" + response;
InputStream res = new URL(url).openStream();
JSONObject json = new JSONObject(getJsonResponse(res));
res.close();
return json.getBoolean("success");
} catch (JSONException e) {
LOGGER.error("Can not parse captcha response Json: " + e);
return false;
} catch (MalformedURLException e) {
LOGGER.error("Malformed URL: " + e);
return false;
} catch (IOException e) {
LOGGER.error("Error reading response from captcha verification response: " + e);
return false;
}
}
private static String getJsonResponse(InputStream res) throws IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(res, Charset.forName("UTF-8")));
/*TODO in java 8+ use this and avoid using the external library
return rd.lines().collect(Collectors.joining());
*/
return IOUtils.toString(rd);
}
}

handle 503 error with jquery

I´m using gridfs to store images in a mongoDB. I have an issue when I update images in the background and want to update them on the screen when finished uploading. I fire an event when I have an image document stored in my mongoDB and then I update the screen. It looks like the document is created while uploading the image because if I do it this way, my image is broken with a 503 error (service not available). When I refresh the page the image appears on the screen.
I believe the problem is that I try to get the image when it is still uploading. I would like to do a $.get(imagesURL) and catch the 503 error but I don't know how to do this. If I could catch the error I could do a loop and wait until its uploaded.
Maybe you guys also have better solutions or know how to catch a 503 error using jquery?
I use a normal file input field for the image
(part of my Template Event in meteorjs)
'change #avatarForm': function (event) {
FS.Utility.eachFile(event, function (file) {
Images.insert(file, function (err, fileObj) {
if (err) {
// handle error
} else {
// handle success depending what you need to do
var userId = Meteor.userId();
var imagesURL = {
"profile.image": "/cfs/files/images/" + fileObj._id
};
Meteor.users.update(userId, {$set: imagesURL});
function checkAvatar() {
$.get(imagesURL)
.complete(function () {
Session.set("registerAvatar", "/cfs/files/images/" + fileObj._id);
}).onerror(function () {
console.log("but still uploading");
checkAvatar();
});
console.log("image saved!");
}
checkAvatar();
}
});
});
},
my code should only fire the new image on the screen (url is set as SessionVar) when the image is completed but its not working.
this is my exact error
Failed to load resource: the server responded with a status of 503 (Service Unavailable)
Something like this should work. The pattern is to set a template helper with a reactive data source - in this case, Meteor.user(). When Meteor.user() changes, the template helper will render out the new data without you having to fetch any data manually:
<template name="test">
<div>Profile Image:</div>
{{#if profileImage}}
<div><img src="{{profileImage}}"></div>
{{/if}}
</template>
Template.test.events({
'change #avatarForm': function(event) {
FS.Utility.eachFile(event, function(file) {
Images.insert(file, function(err, fileObj) {
if (err) {
// handle error
} else {
// handle success depending what you need to do
var userId = Meteor.userId();
var profileImage = {
"profile.image.url": fileObj.url(),
"profile.image.id": fileObj._id
};
Meteor.users.update(userId, {
$set: profileImage
});
}
});
});
},
});
Template.test.helpers({
profileImage: function () {
return Meteor.user().profile.image.url;
}
});

Ember data: Rollback createRecord on error

I'm trying to find the best way to avoid adding a record when there's an error using Ember Data:
This is my code:
createUser: function() {
// Create the new User model
var user = this.store.createRecord('user', {
firstName: this.get('firstName'),
lastName: this.get('lastName'),
email: this.get('email')
});
user.save().then(function() {
console.log("User saved.");
}, function(response) {
console.log("Error.");
});
},
I'm validating the schema on backend and returning a 422 Error in case it fails.
If I don't handle the error, the record is added to the site and I also get a console error.
So I did this:
user.save().then(function() {
console.log("User saved.");
}, function(response) {
user.destroyRecord();
});
Which kind of works deleting the record after reading the server response but:
1) I see the record appearing and dissapearing (like a visual glitch to say it somehow).
2) The console error still appears.
Is there a way to better handle this? I mean, is there a way to avoid adding the record when the server returns an error? Is there a way to avoid showing the console error?
Thanks in advance
You'll need to catch the error in the controller and then use deleteRecord() to remove it from the store:
actions: {
createContent() {
let record = this.store.createRecord('post', {
title: ''
});
record.save()
.then(rec => {
// do stuff on success
})
.catch(err => {
record.deleteRecord();
// do other stuff on error
});
}
}

How to prevent error alerts on Fine-Uploader?

Is there any way to prevent alerts where the onError callback is fired?
I only need to capture the error and display it in a different way
Yes, simply override the showMessage option.
For example:
var uploader = new qq.FineUploader({
request: {
endpoint: 'my/endpoint'
},
callbacks: {
onError: function(fileId, filename, reason, maybeXhr) {
//do something with the error
}
},
showMessage: function(message) {
//either include an empty body, or some other code to display (error) messages
}
});

Categories

Resources