Javascript:拦截所有AJAX调用,重点处理服务器异常

背景

上篇文章http://www.cnblogs.com/happyframework/p/3241063.html介绍了如何以AOP的形式处理服务器异常,这让服务器端的编程逻辑变的非常整洁,本文介绍如何在客户端统一处理服务器返回的异常信息。

一点考虑

上篇隐藏了一些概念,即:开发或架构之处,就应当确定哪些异常要返回给UI、哪些异常要写入日志、哪些异常要包装以后返回给UI等等。

AJAX拦截

如何拦截AJAX,不外乎这三种方式:

  1. 注册全局监听函数。
  2. 封装一个全局入口。
  3. 重写或覆盖客户端库的AJAX功能(Javascript是动态语言,可以运行时替换任何东西)。

最简单的莫过于第一种方式,让我们看一下代码:

拦截事件

 1 /// <reference path="/ext/ext-all-debug-w-comments.js" />
 2 Ext.define('Tenoner.AjaxMonitor', {
 3     singleton: true,
 4     requires: ['Ext.Ajax'],
 5 
 6     errorHandlers: [],
 7 
 8     constructor: function () {
 9         var me = this;
10 
11         Ext.Ajax.timeout = 120000;
12 
13         Ext.Ajax.on('requestcomplete', function (connection, response, option) {
14             me.processError(response);
15         });
16 
17         me.callParent(arguments);
18     },
19 
20     addErrorHandler: function (errorHandler) {
21         var me = this;
22 
23         me.errorHandlers.push(errorHandler);
24     },
25 
26     processError: function (response) {
27         var me = this;
28 
29         var result = Ext.decode(response.responseText);
30 
31         if (!result || !result.errorCode) {
32             return;
33         }
34 
35         Ext.Array.each(me.errorHandlers, function (errorHandler) {
36             Ext.Object.each(errorHandler, function (errorCode, handler) {
37                 if (errorCode == result.errorCode) {
38                     handler();
39                 }
40             });
41         });
42     }
43 });

注册一个异常拦截方法

 1         Tenoner.AjaxMonitor.addErrorHandler({
 2             'CM001': function () {
 3                 var current = window;
 4 
 5                 while (current != current.parent) {
 6                     current = current.parent;
 7                 }
 8 
 9                 current.location.href = '/Login.htm';
10             }
11         });

我们还能做哪些?

如果希望自动弹出错误提示,也可以以这种形式处理,这样Javascript代码中也尽可能的是正常的代码。

备注

本文以ExtJs为例,不过思路应当适合所有AJAX框架。

原文地址:https://www.cnblogs.com/happyframework/p/3245004.html