原文:EXTJS4 - Handle Server-side exceptions and message from an Ajax or Rest proxy
作者:Raja
可能要处理的情况:
success(成功)——Ext处理
failure(失败),由于通讯问题——Ext处理
failure(失败),由于服务器端异常——开发人员人员必须处理的响应失败……
解决方案一:
在应用程序控制器中编写以下方法:
//Ajax Response Error Handler
Ext.Ajax.on('requestexception', function(conn, response, options, eOpts) {
var error = response.status + ' - ' + response.statusText;
console.log('Ajax Request Exception! '+error);
if (response.status != 200) {
var errorData = Ext.JSON.decode(response.responseText); console.log('ajax req error:'+errorData.message);
console.log('Ajax request Error', response.status);
}
});
解决方案二:
当在服务器端发生异常时,可以将500作为响应标头,原因作为HTML内容发送回客户端。
store.on('loadexception',
function(a,conn,resp) {
if (resp.status == '304') {
Ext.Msg.alert('Content has not changed');
}else if(resp.status == '200') {
return; //Do nothing
}else if (resp.status == '401') {
Ext.Msg.alert('Authentication required - You need to Login');
}else if (resp.status == '302') {
errorDialog.body.update('Session Has Expired');
errorDialog.show();
}else if(resp.status == '500') {
errorDialog.body.update(resp.responseText);
errorDialog.show();
}else{
errorDialog.body.update('An uncaught exception has occured');
errorDialog.show();
}
}
解决方案三:
当发送Ajax或REST请求时,Ext JS 4代理通常会预期返回的信息包括参数:data、success和message。参数message是可选的,不过当需要将请求结果显示给用户的时候,它就可派上用场了。
function requestMessageProcessor(proxy, response) {
if (response && proxy) {
try {
var responseData = proxy.reader.getResponseData(response);
if (responseData.message) {
var messageDescription = 'Information'; // title of the alert box
var messageIcon = Ext.MessageBox.INFO;
if (!responseData.success)
{
var messageDescription = 'Error';
var messageIcon = Ext.MessageBox.ERROR;
}
Ext.MessageBox.show({
title: messageDescription,
msg: responseData.message,
buttons: Ext.MessageBox.OK,
icon: messageIcon
});
}
}
catch(err) {
// Malformed response most likely
console.log(err);
}
}
}
And here’s the part which should reside in proxy:
proxy: {
...
listeners: {
exception: function(proxy, response, options) {
requestMessageProcessor(proxy, response);
}
},
afterRequest: function(request, success) {
requestMessageProcessor(request.scope, request.operation.response);
}
}