简体   繁体   English

如何在 Try-Catch 块中围绕错误打印行号

[英]How to print line number around error in Try-Catch block

My script has several try-catch block which sends email about the error message.我的脚本有几个 try-catch 块,用于发送有关错误消息的电子邮件。 It works but only one simple line of error message is sent.它可以工作,但只发送一行简单的错误消息。 What I want is the line number around the error and more descriptive messages to help me identify where the error is happening.我想要的是错误周围的行号和更多描述性消息,以帮助我确定错误发生的位置。

You can try this (I stole it somewhere), the first converts all info in the catched exception into a string.你可以试试这个(我在某处偷了它),第一个将捕获的异常中的所有信息转换为一个字符串。 The second function can be used to wrap some code and if it throws an excetopn write it somewhere.第二个函数可用于包装一些代码,如果它抛出异常,则将其写入某处。

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));
  }
}

The solution above did not work for me, and I found this article: https://sites.google.com/a/mcpher.com/share/Home/excelquirks/gassnips/whereami上面的解决方案对我不起作用,我找到了这篇文章: https : //sites.google.com/a/mcpher.com/share/Home/excelquirks/gassnips/whereami

The simplest code snippet to test it is:测试它的最简单的代码片段是:

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

You will log this info:您将记录此信息:

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

Line of code (164), file (#Triggers) and function name (testError) is here.代码行 (164)、文件 (#Triggers) 和函数名称 (testError) 在这里。

I've also tried this library ( https://github.com/RomainVialard/ErrorHandler ) but now looked for a simpler solution.我也试过这个库( https://github.com/RomainVialard/ErrorHandler ),但现在寻找一个更简单的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM