【问题标题】:js exception positionjs异常位置
【发布时间】:2023-03-17 06:25:01
【问题描述】:

对于这样的 JavaScript 代码:

try {
    MyJob.process();
} catch(e) {
    console.log("Exception occur!");
}

我在 Chrome 或 FireFox 中运行代码,当异常发生时,“异常发生!”的行号将显示在控制台中,但 MyJob 中的原始异常将不存在。是否有任何解决方案可以显示异常发生的原始位置并保留我在这里写的 try-catch?

【问题讨论】:

    标签: javascript debugging exception


    【解决方案1】:
    window.onerror = function ( msg, url, num ) {
       alert ( "Error: " + msg + "\nURL: " + url + "\nLine: " + num );
       return true;
    };
    

    这将显示大部分错误。

    在catch块中添加:

    catch(e) {
        console.log( e.name + ": " + e.message );
    }
    

    更多关于JavaScriptkit的错误处理

    如果 try/catch 块在函数内部,您可以利用 arguments.callee mdn msdn

    function foo() {
        try {
            someFunction();
        }
        catch (e) {
            var f = arguments.callee.toString().substr ( "function ".length);
            f = f.substr(0, f.indexOf('('));
            alert ( "Error type : " + e.name + "\nError : " + e.message + "\nIn function : " + f );
        }
    }
    

    结果将是:

    Error type : ReferenceError
    Error : someFunction is not defined
    In function : foo
    

    【讨论】:

      【解决方案2】:

      暂时注释掉 trycatch,然后使用 Chrome(或 Firefox)JavaScript 调试工具单步执行。

      //try {
          MyJob.process();
      /*} catch(e) {
          console.log("Exception occur!");
      }*/
      

      确定问题后,移除 cmets 恢复原来的错误处理。

      【讨论】:

        猜你喜欢
        • 2017-08-02
        • 1970-01-01
        • 1970-01-01
        • 2021-05-23
        • 1970-01-01
        • 2023-03-29
        • 2020-04-17
        • 1970-01-01
        • 2021-09-15
        相关资源
        最近更新 更多