何时在NODE中使用错误中间件功能

时间:2016-10-10 13:40:48

标签: node.js express error-handling

对于POST请求中缺少字段的情况,我是否应该使用表达式处理中间件函数?

function (req, res, next) {

    if (!req.body.mandatoryField){
        var err = new Error("missing field);
        err.status(400);
        next(err); // send response from error middleware
    }

}

或者我应该将其保存用于导致错误的案例:

model.save(function(err){
     next(err);
 }

换句话说,在POST请求过度杀戮中输入错误是错误吗?

或者我应该直接回复400状态响应,而不会抛出错误。

2 个答案:

答案 0 :(得分:0)

这实际上取决于你的api的设计以及谁会消耗它。如果您正在编写自己的前端并且可以处理HTTP 400错误响应的含义,那么让数据库出错可能会简单得多。

如果您想要更细粒度的验证,那么在路线(或通过中间件)中进行验证是可行的方法:)

答案 1 :(得分:0)

我不会。我会保存中间件错误处理以将错误发送到日志记录服务。通常,您可以拦截一般错误并在继续之前简单地记录它。如果你把它作为一个中间件,你将拦截每个请求,这在大多数情况下是不必要和脆弱的。

通常,使用jQuery在客户端上会发生这种验证,这样就可以节省数据库的访问。

以下是我使用中间件处理错误的方法:

//uncaught exception in the application/api, etc.   Express will pass the err param.  This doesn;t look for specific errors, it will log any general error it sees.
app.use(function(err, req, res, next) {
    //send to logging service.
    next(err);
});
//uncaught exception in Node
if (process.env.NODE_ENV === 'production' || appConfig.env === 'production') { // [2]
    process.on('uncaughtException', function(err) {
        console.error(err.stack); // [3]
        //log error, send notification, etc

    }, function(err) {
        if (err) {console.error(err);}
        process.exit(1); // [5]
    });
}
相关问题