微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 JavaScript 中没有堆栈跟踪的情况下记录错误消息?

如何解决如何在 JavaScript 中没有堆栈跟踪的情况下记录错误消息?

我想在不退出程序的情况下记录发生的错误,因此我将可能引发错误代码在这样的 try-catch 块中

try
{
    let query = parseStatement(input); // might throw an error
    console.log(query);
}
catch (err)
{
    console.error(err); // logs the entire error with stack trace
}
finally
{
    this.prompt();
}

我想获得的输出是没有完整堆栈跟踪的错误消息。 类似的东西:

Error: Missing semicolon at the end of statement: <statement>

而不是

Error: Missing semicolon at the end of statement: <statement>
    at error (/home/nic/dev/nodedb/src/errors.js:5:11)
    at Function.tokenize (/home/nic/dev/nodedb/src/tokens.js:53:13)
    at parseStatement (/home/nic/dev/nodedb/src/sql.js:35:24)
    at Shell.onData (/home/nic/dev/nodedb/src/shell.js:49:25)
    at ReadStream.emit (node:events:394:28)
    at addChunk (node:internal/streams/readable:312:12)
    at readableAddChunk (node:internal/streams/readable:287:9)
    at ReadStream.Readable.push (node:internal/streams/readable:226:10)
    at TTY.onStreamRead (node:internal/stream_base_commons:190:23)

解决方法

来自documentation

Error 对象具有 .message 属性,因此无需打印整个错误,只需

console.error(error.message);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。