Nodejs如何让expressjs 异常不退出
Nodejs如何让expressjs 异常不退出
在开发expressjs应用时,当程序遇到错误时就会异常退出,怎么才能让它异常了却不退出整个程序
8 回复
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}`);
});
解释
-
全局错误处理中间件:
app.use((err, req, res, next) => {...})
定义了一个全局错误处理中间件。- 这个中间件会捕获所有传递给它的错误,并发送一个500状态码的错误响应给客户端。
- 通过这种方式,你可以自定义错误响应的内容,以便更好地与客户端沟通。
-
捕获未处理的异常和拒绝:
process.on('uncaughtException', ...)
和process.on('unhandledRejection', ...)
用于捕获未处理的异常和未处理的拒绝。- 如果某个地方抛出了一个未被捕获的异常或未处理的拒绝,这些事件处理器将被触发,打印相关信息到控制台。
通过上述方法,你可以确保即使在Express应用中发生了异常,整个程序也不会退出。