error.cause


如果存在,error.cause 属性是 Error 的根本原因。 当捕获一个错误并抛出一个带有不同信息或代码的新错误时,它用于仍然能够访问原始错误。

【If present, the error.cause property is the underlying cause of the Error. It is used when catching an error and throwing a new one with a different message or code in order to still have access to the original error.】

error.cause 属性通常通过调用 new Error(message, { cause }) 设置。如果未提供 cause 选项,构造函数不会设置该属性。

【The error.cause property is typically set by calling new Error(message, { cause }). It is not set by the constructor if the cause option is not provided.】

此属性允许将错误进行链式处理。在序列化 Error 对象时,如果设置了 error.causeutil.inspect() 会递归地序列化它。

【This property allows errors to be chained. When serializing Error objects, util.inspect() recursively serializes error.cause if it is set.】

const cause = new Error('The remote HTTP server responded with a 500 status');
const symptom = new Error('The message failed to send', { cause });

console.log(symptom);
// Prints:
//   Error: The message failed to send
//       at REPL2:1:17
//       at Script.runInThisContext (node:vm:130:12)
//       ... 7 lines matching cause stack trace ...
//       at [_line] [as _line] (node:internal/readline/interface:886:18) {
//     [cause]: Error: The remote HTTP server responded with a 500 status
//         at REPL1:1:15
//         at Script.runInThisContext (node:vm:130:12)
//         at REPLServer.defaultEval (node:repl:574:29)
//         at bound (node:domain:426:15)
//         at REPLServer.runBound [as eval] (node:domain:437:12)
//         at REPLServer.onLine (node:repl:902:10)
//         at REPLServer.emit (node:events:549:35)
//         at REPLServer.emit (node:domain:482:12)
//         at [_onLine] [as _onLine] (node:internal/readline/interface:425:12)
//         at [_line] [as _line] (node:internal/readline/interface:886:18)