简体   繁体   English

Expressjs-使用中间件处理错误

[英]Expressjs - Handling Errors With Middleware

I'm building an API (using Expressjs v4) and typically I've dealt with errors within the route rather than using middleware. 我正在构建一个API(使用Expressjs v4),通常我处理的是路由中的错误,而不是使用中间件。 For example: 例如:

router.use('/', function(req, res, next) {
  ...
  if (err)
    return res.status(500).send({type: "serverError", message: "Something has gone wrong on our end."});
}

I now realise that middleware is the "way to go." 我现在意识到中间件是“前进的道路”。 I've seen the rather limited documentation on the Expressjs site here: http://expressjs.com/guide/error-handling.html but still unsure of a few things. 我已经在Expressjs网站上看到了相当有限的文档: http ://expressjs.com/guide/error-handling.html,但仍然不确定。

I've added in the server.js : 我在server.js添加了:

function errorHandler(err, req, res, next) {

}

but how do I supposed to handle the different types of errors (400,404,500 etc)? 但是我应该如何处理不同类型的错误(400,404,500等)?

I'm finding myself writing 3 lines of code each time an error occurs: 我发现自己每次发生错误时都会编写3行代码:

//A route
var err = new Error();
err.status = 404;
return next(err);

and I can access the status using: 我可以使用以下方式访问状态:

function errorHandler(err, req, res, next) {
  console.log(err.status);
  if(err.status == "400")
    //do something
  else
    //etc etc
}

Surely there's an easier way than this? 当然有比这更简单的方法吗? Am I missing something? 我想念什么吗?

You should create your own Error type that allows you to provide all the information necessary to act on the error. 您应该创建自己的错误类型,该类型允许您提供执行错误所需的所有信息。

var util = require('util');

function HttpError(message, statusCode){
    this.message = message;
    this.statusCode = statusCode;
    this.stack = (new Error()).stack;
}

util.inherits(Error, HttpError);
module.exports = HttpError;

Then include your new error object in your code and use it like 然后在代码中包含新的错误对象,并像使用它一样

next(new HttpError('Not Found', 404));

Or you could go crazy and implement an error type for each response code pre-populating the statusCode part. 或者,您可能会发疯并为每个预填充statusCode部分的响应代码实现错误类型。

Ref: What's a good way to extend Error in JavaScript? 参考: 在JavaScript中扩展Error的好方法是什么?

Instead manually creating error , you can delegate that error like below. 代替手动创建error ,您可以像下面这样委派该错误。

return next(err);

And your error will go deep down all the routes defined until it find routes with below signature. 您的错误将深入所有定义的路由,直到找到具有以下签名的路由。

app.use(function (err, req, res, next) {

});

You can see the err argument in above route. 您可以在上述路线中看到err参数。

Ideally you can use below two methods for both DEVELOPMENT & PRODUCTION environment. 理想情况下,您可以在开发和生产环境中使用以下两种方法。

if (process.env.NODE_ENV === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        logger.log('info', err.message + " expected URL was " + req.url);
        res.status(err.status).send(err.status, {
            message: err.message,
            error  : err
        });
    });
}

app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    logger.log('error', err.message + " expected URL was " + req.url);
    res.status(err.status).send(err.status, {
        message: err.message,
        error  : {}
    });

});

You can capture actual populated error object in there. 您可以在其中捕获实际填充的错误对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM