javascript 在Node中全局处理异常的最佳方法,js与Express 4?

rqcrx0a6  于 2023-04-28  发布在  Java
关注(0)|答案(5)|浏览(125)

我们在www.example中有异常过滤器 www.example.com 。Js Express 4也是?
我尝试了以下文章,但没有找到所需的解决方案。
http://www.nodewiz.biz/nodejs-error-handling-pattern/
我也试过下面的app。js

process.on('uncaughtException', function (err) {
  console.log(err);
})

参考文献:http://shapeshed.com/uncaught-exceptions-in-node/
任何帮助都是值得的。

vptzau2j

vptzau2j1#

错误可能来自不同的位置并在不同的位置捕获,因此建议在处理所有类型错误的集中式对象中处理错误。例如,错误可能发生在以下位置:

  1. Web请求中出现SYNC错误时的Express中间件
app.use(function (err, req, res, next) {
//call handler here
});
  1. CRON作业(计划任务)
    3.您的初始化脚本
    4.测试代码
    5.来自某处的未捕获错误
process.on('uncaughtException', function(error) {
 errorManagement.handler.handleError(error);
 if(!errorManagement.handler.isTrustedError(error))
 process.exit(1)
});

6.未处理的promise拒绝

process.on('unhandledRejection', function(reason, p){
   //call handler here
});

然后,当你捕获错误时,将它们传递给一个集中的错误处理程序:

module.exports.handler = new errorHandler();

function errorHandler(){
    this.handleError = function (error) {
        return logger.logError(err).then(sendMailToAdminIfCritical).then(saveInOpsQueueIfCritical).then(determineIfOperationalError);
    }

更多信息read bullet 4' here(+其他最佳实践和超过35个报价和代码示例)

8i9zcol2

8i9zcol22#

在express中,附加一个catch all错误处理程序是标准做法。准系统错误处理程序如下所示

// Handle errors
app.use((err, req, res, next) => {
    if (! err) {
        return next();
    }

    res.status(500);
    res.send('500: Internal server error');
});

除此之外,您还需要捕获任何可能发生的错误,并将它们作为next()中的参数传递。这将确保catch all处理程序捕获错误。

zpgglvta

zpgglvta3#

在node中添加全局异常处理程序是process上的事件。使用process.on来捕获它们。

process.on('uncaughtException', (err) => {
   console.log('whoops! there was an error');
});
7fyelxc5

7fyelxc54#

Express js v4全局错误处理。

app.use((_req,_res,next)=>{
    const error = new Error("Not Found")
    error.status= 404;
    next(error)
})

app.use((error,_req,res,_next)=>{
    if(error.status){
        return res.status(error.status).json({
            message:error.message,
        })
    }

    res.status(500).json({message:'something wrong'})
})
lb3vh1jj

lb3vh1jj5#

为expressjs中的所有路由编写一个中间件,如下所示

function asyncTryCatchMiddleware(handler){
    return async (req,res,next) => {
       try{
           await handler(req,res);
       } catch(e) {
           next(e)
       }
    };
}

您可以像这样使用中间件:

router.get('/testapi',asyncTryCatchMiddleware(async (req,res)=>{
    res.send();
}));

相关问题