Node.js 进程未处理的拒绝事件

Node.js 进程未处理的拒绝事件

进程是在Node.js中维护跟踪并包含有关正在计算机上运行的特定Node.js进程的所有信息的全局对象。当未处理的Promise被拒绝时,将发出未处理的拒绝事件。Node.js会向终端输出一个UnhandledPromiseRejectionWarning警告,并迅速结束进程。全局的Node.js进程具有未处理的拒绝事件。当出现未处理的拒绝并且没有处理程序在Promise链中处理它时,将触发此事件。

Syntax:

process.on("unhandledRejection", callbackfunction)

参数: 该方法接受以下两个参数。

  • unhandledRejection: 它是进程中的发射事件的名称。
  • 回调函数: 它是该事件的事件处理程序。

返回值: 该方法的返回类型是void。

示例1: 注册一个unhandledRejection事件监听器的基本示例。

// The unhandledRejection listener 
process.on('unhandledRejection', error => { 
    console.error('unhandledRejection', error); 
}); 
  
// Reject a promise 
Promise.reject('Invalid password'); 

运行步骤:

使用以下命令运行 index.js 文件:

node index.js

输出:

unhandledRejection Invalid password

示例2: 为了证明当您的链中没有promise rejection处理程序时,unhandledRejection监听器将执行。

// The unhandledRejection listener 
process.on('unhandledRejection', error => { 
    // Won't execute 
    console.error('unhandledRejection', error); 
}); 
  
// Reject a promise 
Promise.reject('Invalid password') 
    .catch(err => console.error(err)) 

运行步骤: 使用以下命令运行 index.js 文件:

node index.js

输出:

Invalid password

参考: https://nodejs.org/api/process.html#process_event_unhandledrejection

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程