Node UnhandledPromiseRejectionWarning 的处理方法

30 min read

UnhandledPromiseRejectionWarning

at ChildProcess.exithandler (child_process.js:308:12)
    at ChildProcess.emit (events.js:314:20)
    at maybeClose (internal/child_process.js:1022:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:287:5)
(node:1731) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1731) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Promise API 中有 .catch() 这个方法,可以用来处理捕捉 rejection 进行处理

new Promise((resolve, reject) => {
  setTimeout(() => reject('error'), 500);
})
.catch(error => console.log('caught', error))


new Promise(() => { throw new Error('exception!'); })
.catch(error => console.log('caught', error.message))

如何从 Node.js 程序退出

process 核心模块提供了一种便利的方法,可以以编程的方式退出 Node.js 程序:process.exit()

当 Node.js 运行此行代码时,进程会被立即强制终止。

这意味着任何待处理的回调、仍在发送中的任何网络请求、任何文件系统访问、或正在写入 stdoutstderr 的进程,所有这些都会被立即非正常地终止。

可以传入一个整数,向操作系统发送退出码:

process.exit(1)

默认情况下,退出码为 0,表示成功。 不同的退出码具有不同的含义,可以在系统中用于程序与其他程序的通信。

let a = 1;

while (true){
    console.log('a:',a)
    if (a===1000){
        process.exit(1);
    }
    a++;
}