【问题标题】:How to log an error's message without stack trace in JavaScript?如何在 JavaScript 中记录没有堆栈跟踪的错误消息?
【发布时间】:2021-06-21 15:01:55
【问题描述】:

我想在不退出程序的情况下记录发生的错误,因此我将可能引发错误的代码附在 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)

【问题讨论】:

    标签: javascript node.js error-handling stack-trace traceback


    【解决方案1】:

    来自documentation

    Error 对象有一个.message 属性,所以不用打印整个错误,只需

    console.error(error.message);
    

    【讨论】:

    • 所以不在博客中
    • @LawrenceCherone SO 上没有这样的问题/答案,所以我认为其他人可能会偶然发现需要在没有整个堆栈跟踪的情况下记录错误。我认为这个问题/答案可能会节省其他人阅读文档的时间
    • 即使是纯文本也会有堆栈跟踪。不为自己。但是对于你写console.error()的地方。
    猜你喜欢
    • 2010-12-29
    • 2015-08-04
    • 2015-02-06
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 2014-08-12
    相关资源
    最近更新 更多