0

嘿伙计们,我想在 express 中实现中央错误处理,我已经做到了。

app.use(function(err,req,res,next){
    logger.error(err);
    utils.jsonOutHandler(err,null,res);
    next(err);
});

app.get('/',(req,res)=>{
    throw new Error('Testing');
});

我还做了一个特殊的 jsonOutHandler 方法,它向用户发送正确的响应。

function jsonOutHandler(err, result, out) {
    if (err) {
        let status = 500;
        const message = 'Something broke';
        if (err instanceof DbError) {
            status = 500;
        }
        if (err instanceof ValidationError) {
            status = 400;
        }
        if (err instanceof SystemError) {
            status = 500;
        }
        out.status(status).send({message});
        return;
    }

    out.status(result.status).send({data: result.data});

}

但是,每当我在“/”路由上抛出错误时,我的错误处理程序都不会被触发。为什么?

4

1 回答 1

1

Express 是基于中间件的,所以,如果你想捕捉中间件内部的错误,你应该调用错误中间件:

app.get('/',(req,res)=>{
    next(new Error('Testing'));
});

/**
 * middleware to catch errors happened before this middleware
 * express knows this middleware is for error handling because it has
 * four parameters (err, req, res, next)
 **/
app.use((err, req, res, next) => {
  res.status(500).send({
    message: err.message,
  });
});

我希望您可以根据您的要求调整此示例。要记住的是错误中间件可以从以前的中间件中使用。在您的示例中,您无法捕获错误,因为您的中间件是在主路由器 app.get('/') 之前定义的

于 2020-04-06T21:22:41.213 回答