【问题标题】:How to print line number around error in Try-Catch block如何在 Try-Catch 块中围绕错误打印行号
【发布时间】:2012-11-22 23:02:11
【问题描述】:

我的脚本有几个 try-catch 块,用于发送有关错误消息的电子邮件。它有效,但只发送了一行简单的错误消息。我想要的是错误周围的行号和更多描述性消息,以帮助我确定错误发生的位置。

【问题讨论】:

    标签: javascript google-apps-script error-handling try-catch


    【解决方案1】:

    你可以试试这个(我在某个地方偷的),首先将捕获的异常中的所有信息转换为字符串。第二个函数可用于包装一些代码,如果它抛出异常,则将其写入某处。

    function catchToString (err) {
      var errInfo = "Catched something:\n"; 
      for (var prop in err)  {  
        errInfo += "  property: "+ prop+ "\n    value: ["+ err[prop]+ "]\n"; 
      } 
      errInfo += "  toString(): " + " value: [" + err.toString() + "]"; 
      return errInfo;
    }
    function catched (f) {
      try {
        f ();
      }
      catch(err) { 
        Logger.log (catchToString (err));
      }
    }
    

    【讨论】:

    • 或者,如果您只想要堆栈跟踪,请使用 err["stack"]
    【解决方案2】:

    上面的解决方案对我不起作用,我找到了这篇文章: https://sites.google.com/a/mcpher.com/share/Home/excelquirks/gassnips/whereami

    测试它的最简单的代码sn-p是:

    function testError() {
      try {
        SpreadsheetApp.openById('Boooo');  
      } catch(err) {
        Logger.log(err.stack);
      }
    }
    

    您将记录此信息:

    Exception: Unexpected error while getting the method or property openById on object SpreadsheetApp.
    at testError (#Triggers:164:20)
    at __GS_INTERNAL_top_function_call__.gs:1:8
    

    代码行(164)、文件(#Triggers)和函数名(testError)在这里。

    我也尝试过这个库 (https://github.com/RomainVialard/ErrorHandler),但现在正在寻找更简单的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 2017-03-04
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多