Nodejs如何让expressjs 异常不退出

Nodejs如何让expressjs 异常不退出

在开发expressjs应用时,当程序遇到错误时就会异常退出,怎么才能让它异常了却不退出整个程序

8 回复

Node.js 如何让 Express.js 异常不退出

在开发基于 Node.js 的 Express.js 应用时,你可能会遇到一些未处理的异常,导致整个应用程序意外退出。为了确保应用程序在发生错误时仍然能够继续运行,你可以通过以下几种方法来捕获和处理这些异常。

1. 使用 try...catch 捕获同步异常

对于同步代码中的异常,你可以使用传统的 try...catch 语句来捕获并处理它们。例如:

app.get('/', (req, res) => {
    try {
        // 这里可能会抛出异常
        throw new Error('Something went wrong!');
    } catch (error) {
        console.error(error);
        res.status(500).send('Internal Server Error');
    }
});

2. 使用中间件捕获异步异常

对于异步代码(如数据库操作、文件读写等),你需要使用中间件来捕获这些异常。Express 提供了一个全局的错误处理中间件,可以用来捕获所有未处理的异常:

// 定义一个全局错误处理中间件
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

// 在路由中使用异步函数
app.get('/async', async (req, res, next) => {
    try {
        // 这里可能会抛出异步异常
        const result = await someAsyncFunction();
        res.send(result);
    } catch (error) {
        next(error); // 将错误传递给错误处理中间件
    }
});

3. 全局异常处理

你还可以设置全局的异常处理器来捕获任何未被捕获的异常,以防止它们导致应用程序退出:

process.on('uncaughtException', (error) => {
    console.error(`Caught exception: ${error}`);
});

process.on('unhandledRejection', (reason, promise) => {
    console.error(`Unhandled Rejection at: ${promise} reason: ${reason}`);
});

通过以上方法,你可以有效地捕获和处理各种异常,从而确保你的 Express.js 应用程序即使在发生错误时也能保持运行状态。


forever or nodemon or pm2 or …

nodejs API 的 domain模块 能满足你

try {} catch()

process.on(‘uncaughtException’, function (err) { //do something like log error });

var D = require("domain");
var d = D.create();

d.on("error" , function(){
   // error handle
})

d.run(function(){
   // app code
});


签名: 交流群244728015 《Node.js 服务器框架开发实战》 http://url.cn/Pn07N3

使用奶妈进程守护吧

要在Express.js应用中处理异常而不让整个程序退出,可以通过全局错误处理中间件来捕获未处理的异常。这样可以确保即使发生了异常,应用程序也不会退出。

示例代码

const express = require('express');
const app = express();

// 定义一个全局错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack); // 打印堆栈跟踪到控制台
  res.status(500).send('Something broke!'); // 发送错误响应给客户端
});

// 示例路由
app.get('/', (req, res) => {
  throw new Error('Oops! Something went wrong.');
});

// 捕获未处理的异常
process.on('uncaughtException', (error) => {
  console.log(`Uncaught Exception: ${error.message}`);
});

process.on('unhandledRejection', (reason, promise) => {
  console.log(`Unhandled Rejection at: ${promise} reason: ${reason}`);
});

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

解释

  1. 全局错误处理中间件:

    • app.use((err, req, res, next) => {...}) 定义了一个全局错误处理中间件。
    • 这个中间件会捕获所有传递给它的错误,并发送一个500状态码的错误响应给客户端。
    • 通过这种方式,你可以自定义错误响应的内容,以便更好地与客户端沟通。
  2. 捕获未处理的异常和拒绝:

    • process.on('uncaughtException', ...)process.on('unhandledRejection', ...) 用于捕获未处理的异常和未处理的拒绝。
    • 如果某个地方抛出了一个未被捕获的异常或未处理的拒绝,这些事件处理器将被触发,打印相关信息到控制台。

通过上述方法,你可以确保即使在Express应用中发生了异常,整个程序也不会退出。

回到顶部