http 状态代码 NodeJS/ExpressJS 错误



错误处理程序:

//error handler
app.use(function(err, req, res, next){
    console.error({error: err});
    //res.status(500);
    res.format({
        'text/html': function() {
            res.render('error', {error: err.message});
        },
        'application/json': function() {
            res.json({'error': err.message});
        }
    });
});

路线/404:

exports.someRoute = function(req, res, next) {
    ...
    if (!page) {
        return next(new Error('Page not found.')));
    }
    ...
};

在错误处理程序中,如何获得适当的错误状态代码?

您需要

以某种方式将该信息放入错误对象中,要么使用简单的属性(如 error.status),要么将其基于类层次结构(如 error instanceof NotFound)。

但是,404 是如此普遍,以至于我只是在req中添加逻辑以使用类似 req.notFound(message) 的东西来处理它,甚至只是在处理 404 的最后路由中使用next('route')

无论如何,很多选择。

最新更新