PDA

View Full Version : Store + RestProxy & server error handling



netknight
13 Jan 2014, 9:33 AM
Hi, I'm trying to figure out how can I handle server responses with status code != 200?
Afaik, I use Rest service it is common way to tell about exceptions via status codes:
200 - OK (no error)
400 - Bad Request (incorrect request or its parameters)
404 - Resource Not Found (server down/incorrect url/entity not found in DB)
401 & 403 - Authentication Errors (user is not logged in or not authorised for operation)
500 - General Server Error (In most cases something is broken)

Are there any ways to catch such exceptions and handle them? For example when user session is expired I'd like to show user a login page or warn him about server problem if status 500 is returned etc.

I've read source code for all types of Stores, Proxies and Readers and see that in any case there is expectation that status code 200 will be returned in any case and application errors are passed in body content (for example form validation errors). But it is not true for real world and it breaks REST standards! I don't wan't to change my backend to meet ExtJS expectations because it is used by other clients also, but I believe there is a way to handle non 200 status codes. I've already found some hack-ways but maybe there is official way?

Gary Schlosberg
13 Jan 2014, 11:46 AM
Not sure about an official way, but perhaps these nodes will help:
http://www.sencha.com/forum/showthread.php?237267
http://www.sencha.com/forum/showthread.php?259339

netknight
14 Jan 2014, 7:10 AM
OK, I'll show my solution and would like to have some comments if this is adequate way. But I'm sure this MUST be inside the ExtJS code because if we title proxy as a "RestProxy" then we must be sure that it is inline with REST specification. Currently REST is partially supported.


Here is my code:

Ext.define('My.proxy.RestProxy', {
extend: 'Ext.data.proxy.Rest',
alias: 'proxy.myrest',
constructor: function(config) {
this.addEvents('authError', 'validationError', 'serverError');
return this.callParent(arguments);
},
processResponse: function(success, operation, request, response, callback, scope) {
if (response.status !== 200) {
this.handleError(response);
}
return this.callParent(arguments);
},
handleError: function(response) {
switch (response.status) {
case 400:
return this.fireEvent('validationError', response);
case 401:
return this.fireEvent('authError', true);
case 403:
return this.fireEvent('authError', false);
case 500:
return this.fireEvent('serverError', response);
default:
return this.fireEvent('serverError', response);
}
}
});



And we could subscribe to error like this:


store.getProxy().on('serverError', function(response) {
// DO SOMETHING
});