代码之家  ›  专栏  ›  技术社区  ›  Nizzy

javascript将自定义错误处理程序设置为第三方插件或模块

  •  0
  • Nizzy  · 技术社区  · 14 年前

    有人能帮帮我吗?谢谢您

    Function.prototype.setErrorHandler = function(f) {
     if (!f) {
      throw new Error('No function provided.');
     }
     var that = this;
     var g = function() {
      try {
       var a = [];
       for(var i=0; i<arguments.length; i++) {
        a.push(arguments[i]);
       }
       that.apply(null,a);
      }
      catch(e) {
       return f(e);
      }
     };
     g.old = this;
     return g;
    };
    
    
    function myHandler(e) {
     alert(e.message)
    };
    
    // my Core library object
    (function(){
     if (typeof window.Core === 'undefined') {
      var Core = window.Core = function() {
       this.addPlugin = function(namespace, obj){
        if (typeof this[namespace] === 'undefined') {
         if (typeof obj === 'function') {
          obj.setErrorHandler(myHandler);
         } else if (!!obj && typeof obj === 'object') {
          for (var o in obj) {
           if (obj.hasOwnProperty(o) && typeof obj[o] === 'function') {
            obj[o].setErrorHandler(myHandler);
           }
          }
         }
    
         this[namespace] = obj;
    
         return true;
        } else {
         alert("The namespace '" + namespace + "' is already taken...");
         //return false;
        }
       };
      };
    
      window.Core = new Core();
     }
    })();
    
    // test plugin
    (function(){
     var myPlugin = {
      init: function() {},
      conf: function() {
       return this.foo.x; // error here
      }
     };
    
     Core.addPlugin("myPlugin", myPlugin);
    })();
    
    // test
    Core.myPlugin.conf(); // supposed to alert(e.message) from myHandler()
    
    1 回复  |  直到 14 年前
        1
  •  0
  •   bobince    14 年前

    setErrorHandler 在上面的代码中没有 函数的错误处理程序。JavaScript不能让您更改函数对象内的调用代码。

    相反,它生成调用它的函数的包装版本,并返回它。

    obj.setErrorHandler(myHandler);
    

    无法工作,因为返回的包装函数被丢弃,未分配给任何对象。

    你可以说:

    obj[o]= obj[o].setErrorHandler(myHandler);
    

    尽管我有点担心用不同的包装版本替换函数的后果。这不一定适用于所有情况,而且肯定会混淆第三方代码。至少,您希望确保不将函数包装两次,并且还保留调用时间 this 包装中的值:

    that.apply(this, a);
    

    arguments 一个阵列。通过考试是有效的 论据 apply .)