How to Handle errors on ExtJs - javascript

I want to be able to catch any error thrown on my screen. So far my code is this:
Ext.application({
errorHandler:function(err){
alert(err.msg);
return true;
},
requires: [
'Ext.ux.ajax.JsonSimlet',
'Ext.ux.ajax.SimManager'
],
views: [
'Admin.view.something',
'Admin.view.somethingController'
],
name: 'Admin',
launch : function() {Ext.create('Admin.view.something');
Ext.Error.notify = false;
Ext.Error.handle = this.errorHandler;
}
});
The problem is, I have some objects that may be undefined. If I do something like undefined.properties, the error handling doesn't catch it.
I know about functions like "Ext.isDefined()", but for this case I really need to handle all generic errors in the same way.

Ext.Error.handle only handles errors raised by Ext.raise according to the documentation.
A solution to handle plain javascript errors is the error event on the browsers window.
You can attach an handler with window.addEventListener('error', function(event) { ... }) to it.
The following code should catch all errors in your project.
launch : function() {
Ext.Error.notify = false;
Ext.Error.handle = this.errorHandler;
window.addEventListener('error', this.errorJsHandler);
Ext.create('Admin.view.something');
},
errorJsHandler: function(err) { // err = ErrorEvent Object https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent
alert(err.message);
return true; // prevent the firing of the default event handler
},

Related

How to use a default reject handler in Promise

I make Ajax requests with a Promise and usually handle errors the same way. So e.g. if a 404 happens, then I would just display a standard error message by default. But in some cases I want to do something else.
Note: I'm using ExtJS 4 to do the actual Ajax request, but this issue is not specific to ExtJS. ExtJS does not use Promises, so I'm basically converting their API to a Promise API.
This is the code:
var defaultErrorHandler = function(response) {
// do some default stuff like displaying an error message
};
var ajaxRequest = function(config) {
return new Promise(function(fulfill, reject) {
var ajaxCfg = Ext.apply({}, {
success: function(response) {
var data = Ext.decode(response.responseText);
if (data.success) {
fulfill(data);
} else {
defaultErrorHandler(response);
reject(response);
}
},
failure: function(response) {
defaultErrorHandler(response);
reject(response);
}
}, config);
Ext.Ajax.request(ajaxCfg);
});
};
// usage without special error handling:
ajaxRequest({url: '/some/request.json'}).then(function(data) {
// do something
});
// usage with special error handling:
ajaxRequest({url: '/some/request.json'}).then(function(data) {
// do something
}, function(response) {
// do some additional error handling
});
Now the problem: The "usage without special error handling" does not work, because if I do not provide a reject function, it will throw an error. To fix this, I am forced to provide an empty function, like so:
// usage without special error handling:
ajaxRequest({url: '/some/request.json'}).then(function(data) {
// do something
}, function() {});
Having to provide an empty function every time (and in my code base this will be hundreds of times) is ugly, so I was hoping there was a more elegant solution.
I also do not want to use catch() since that would catch ALL errors thrown, even if it happens in the fulfill function. But actual errors happening in my code should not be handled, they should appear in the console.
There is no such thing a "default error handler for all promises", unless you are looking to provide an unhandled rejection handler. That would however not be restricted to the promises for your ajax requests.
The simplest and best solution would be to just expose your defaultErrorHandler and have every caller explicitly pass it the then invocation on your promise. If they don't want to use it, they either need to provide their own special error handler or they will get a rejected promise. This solution provides maximum flexibility, such as allowing to handle the rejection further down the chain.
If that is not what you want to do, but instead require immediate handling of the ajax error, your best bet is to override the then method of your returned promises:
function defaultingThen(onfulfill, onreject = defaultErrorHandler) {
return Promise.prototype.then.call(this, onfulfill, onreject);
}
function ajaxRequest(config) {
return Object.assign(new Promise(function(resolve, reject) {
Ext.Ajax.request({
...config,
success: function(response) {
var data = Ext.decode(response.responseText);
if (data.success) {
resolve(data);
} else {
reject(response);
}
},
failure: reject,
});
}), {
then: defaultingThen,
});
}

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
}
});

Extjs 3.3 IE8 chained events is breaking

This one is wired.
This fires from a grid toolbar button click:
// fires when the client hits the add attachment button.
onAddAttachmentClick: function () {
var uploadAttachmentsWindow = new Nipendo.ProformaInvoice.Attachment.UploadWindow({
invoice: this.invoice,
maxFileSizeInMB: this.maxFileSizeInMB
});
uploadAttachmentsWindow.on('uploadcomplete', function (win, message) {
if (message.msg !== 'success') {
return;
}
win.close();
var store = this.getStore();
store.setBaseParam('useCache', false);
store.load();
this.fireEvent(
'attachmentuploaded',
this.invoice.ProformaInvoiceNumber,
this.invoice.VendorSiteID,
this.invoice.CustomerSiteID);
}, this);
uploadAttachmentsWindow.show();
} // eo onAddAttachmentClick
This is what happens on the uploadcomplete event:
this.uploadBtn.on('click', function () {
var form = this.uploadForm.getForm();
if (!form.isValid()) {
return;
}
form.submit({
url: 'XXX.ashx',
waitMsg: Nipendo.Localization.UploadingAttachment,
scope: this,
success: function (form, action) {
this.fireEvent('uploadcomplete', this, {
msg: 'success',
response: action.response
});
},
failure: function (form, action) {
switch (action.failureType) {
case Ext.form.Action.CLIENT_INVALID:
this.fireEvent('uploadcomplete', this, {
msg: 'Form fields may not be submitted with invalid values'
});
break;
case Ext.form.Action.CONNECT_FAILURE:
this.fireEvent('uploadcomplete', this, {
msg: 'Ajax communication failed'
});
break;
case Ext.form.Action.SERVER_INVALID:
Ext.Msg.alert(action.result.title, action.result.message);
this.fireEvent('uploadcomplete', this, {
msg: action.result.message
});
break;
}
}
});
}, this);
On IE 8 I am getting this error in the debugger:
I have no idea what object is missing... from my check they are all defined.
Any idea anyone?
Notice that I have an event firing from a listener (I am suspecting it to be the root of the problem).
It is hard to see but the error occuers in ext-all.js in the fire method.
I have found the answer in : https://stackoverflow.com/a/3584887/395890
Problem was I was listing to events is 2 different windows, that is not possible in Ext.
What I have done to solv it was to call the opner window from the pop up window to notify about changes.

how to handle the error in dojo

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*/ });

Categories

Resources