在应用程序脚本 Console.error 函数中添加行编号
Add line numb in apps script Console.error function
我正在使用 console.error() 函数来记录使用应用程序脚本制作的工作表插件的错误。例如:
1 var a = null;
2 a.toString();
3 } catch(error) {
4 console.error('Function_1(): ' + error);
5 }
但是,我的函数比较大,当我遇到类似“can't use toString() on null
”的错误时,我不确定问题出在哪里。
我尝试将它与 throw 一起使用:
1 var a = null;
2 a.toString();
3 } catch(error) {
4 throw 'Function_1(): '+error;
5 }
但是,我得到了抛出的行号:
can't use toString() on null at line 4
,而问题在 line 2
。
我查看了其他主题,例如:
How do you pass back a custom error message from google apps scripts?
但是,它没有回答如何提供正确的行号。
使用 e.lineNumber
其中 e
是错误对象实例。示例:
function myFunction() {
try {
throw new Error('Error message');
} catch(e) {
console.error(e.lineNumber)
}
}
注意:您可以使用 error
或适合您的编码风格的任何其他变量名称来代替 e
。
相关
如果您检查由 catch
块接收的 Error
对象 error
,您可以观察到它有几个可以访问的属性:
try {
...
} catch (error) {
const parts = {};
for (var i in error) {
parts[i] = error[i];
}
console.error({message: "Apps Script error object decomposition", error: error, parts: parts});
}
Stackdriver 日志示例:
因此您可以在日志中包含错误的完整堆栈跟踪,以及文件和行号:
try {
...
} catch (e) {
console.error({
message: "An error occurred",
errMsg: e.message,
line: e.lineNumber,
fileName: e.fileName,
stackTrace: e.stack
});
if (<some conditions>) {
// update message:
e.message = "Unhandled error in so-and-so: " + e.message;
// Re-raise with the same trace info by re-throwing it:
throw e;
}
}
我正在使用 console.error() 函数来记录使用应用程序脚本制作的工作表插件的错误。例如:
1 var a = null;
2 a.toString();
3 } catch(error) {
4 console.error('Function_1(): ' + error);
5 }
但是,我的函数比较大,当我遇到类似“can't use toString() on null
”的错误时,我不确定问题出在哪里。
我尝试将它与 throw 一起使用:
1 var a = null;
2 a.toString();
3 } catch(error) {
4 throw 'Function_1(): '+error;
5 }
但是,我得到了抛出的行号:
can't use toString() on null at line 4
,而问题在 line 2
。
我查看了其他主题,例如: How do you pass back a custom error message from google apps scripts?
但是,它没有回答如何提供正确的行号。
使用 e.lineNumber
其中 e
是错误对象实例。示例:
function myFunction() {
try {
throw new Error('Error message');
} catch(e) {
console.error(e.lineNumber)
}
}
注意:您可以使用 error
或适合您的编码风格的任何其他变量名称来代替 e
。
相关
如果您检查由 catch
块接收的 Error
对象 error
,您可以观察到它有几个可以访问的属性:
try {
...
} catch (error) {
const parts = {};
for (var i in error) {
parts[i] = error[i];
}
console.error({message: "Apps Script error object decomposition", error: error, parts: parts});
}
Stackdriver 日志示例:
因此您可以在日志中包含错误的完整堆栈跟踪,以及文件和行号:
try {
...
} catch (e) {
console.error({
message: "An error occurred",
errMsg: e.message,
line: e.lineNumber,
fileName: e.fileName,
stackTrace: e.stack
});
if (<some conditions>) {
// update message:
e.message = "Unhandled error in so-and-so: " + e.message;
// Re-raise with the same trace info by re-throwing it:
throw e;
}
}