You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何仅记录错误消息而不输出堆栈追踪信息?

实现方案

JavaScript 中抛出的标准 Error 对象自带专属属性和方法,你可以按需选择以下两种实现:

  • 仅输出纯错误描述内容
    直接读取 err.message 属性,该属性仅存储错误的文本描述:
try
{
    let query = parseStatement(input); // 可能抛出错误
    console.log(query);
}
catch (err)
{
    console.error(err.message); 
    // 输出示例:Missing semicolon at the end of statement: <statement>
}
finally
{
    this.prompt();
}
  • 输出带错误类型前缀的完整错误提示(完全匹配你给出的预期格式)
    调用 Error 对象的 toString() 方法,会自动拼接错误类型和错误描述内容:
try
{
    let query = parseStatement(input); // 可能抛出错误
    console.log(query);
}
catch (err)
{
    console.error(err.toString());
    // 输出示例:Error: Missing semicolon at the end of statement: <statement>
}
finally
{
    this.prompt();
}

原理解释

直接将 Error 对象传入 console.error 时,浏览器和 Node.js 环境默认会读取对象的 stack 属性打印完整堆栈信息,主动调用 message 属性或者 toString() 方法只会输出错误描述,不会触发堆栈内容的打印。

内容的提问来源于stack exchange,提问作者Nicholas Obert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 16:06:01