Expressjs - 处理中间件的错误 [英] Expressjs - Handling Errors With Middleware

查看:125
本文介绍了Expressjs - 处理中间件的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建API(使用Expressjs v4),通常我已经处理了路由中的错误,而不是使用中间件。例如:

  router.use('/',function(req,res,next){
.. 。
if(err)
return res.status(500).send({type:serverError,message:有些事情在我们的结尾出了问题。});
}

我现在意识到中间件是走的路,我看到了相当有限的文档在Expressjs网站上: http://expressjs.com/guide/error-handling.html 但仍不确定的一些东西。



我已经在 server.js中添加了

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

}
/ pre>

但是我应该如何处理不同类型的错误(400,404,500等)?



每当发生错误时,我发现自己写了3行代码:

  //路由
var err = new Error();
err.status = 404;
return n ext(err);

我可以使用以下方式访问状态:

  function errorHandler(err,req,res,next){
console.log(err.status);
if(err.status ==400)
//做某事
else
// etc etc
}

当然有一种比这更简单的方法?我错过了什么吗?

解决方案

您应该创建自己的错误类型,允许您提供所有必要的信息错误。

  var util = require('util'); 

函数HttpError(message,statusCode){
this.message = message;
this.statusCode = statusCode;
this.stack =(new Error())。
}

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

然后在您的代码中包含新的错误对象,并使用它像

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

或者你可能会疯狂,并为每个预填充 statusCode part。



参考:什么是一个很好的方法来扩展JavaScript中的错误


I'm building an API (using Expressjs v4) and typically I've dealt with errors within the route rather than using middleware. 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.

I've added in the server.js:

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

}

but how do I supposed to handle the different types of errors (400,404,500 etc)?

I'm finding myself writing 3 lines of code each time an error occurs:

//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.

Ref: What's a good way to extend Error in JavaScript?

这篇关于Expressjs - 处理中间件的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆