快速错误处理-获取状态码 [英] Express Error Handling - Get Status Code

查看:286
本文介绍了快速错误处理-获取状态码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我用express这样定义错误处理中间件:

If I define error handling middleware with express like so:

app.use(function(err,req,res,next){
    // Do Stuff
});

如何获取错误的HTTP状态代码(或者我只是假设它是500) ?

How do I get the HTTP status code of the error(or do I just assume is's a 500)?

谢谢,

阿里

Thanks,
Ari

推荐答案

简而言之,您的代码必须根据您在错误处理中间件中处理的特定错误来确定适当的错误代码。

In short, your code has to decide the appropriate error code based on the specific error you are handling within your error handling middleware.

不一定有HTTP状态此时生成的代码。按照惯例,当我从中间件功能或路由器处理程序功能调用 next(error)时,我放置了 code 属性因此我的错误处理中间件可以执行 res.status(err.code || 500).render('error_page',error); 或类似的事情。但是,是否要针对常见的404错误或仅5XX服务器错误或其他原因使用此方法,完全取决于您。当将错误传递给 next 回调时,表达本身或大多数中间件的东西很少会提供http状态代码。

There is not necessarily an HTTP status code generated at this point. By convention, when I call next(error) from a middleware function or router handler function, I put a code property so my error handling middleware can do res.status(err.code || 500).render('error_page', error); or something along those lines. But it's up to you whether you want to use this approach for your common 404 errors or only 5XX server errors or whatever. Very few things in express itself or most middleware will provide an http status code when passing an error to the next callback.

举一个具体的例子,假设有人试图用我发现已经在数据库中注册的电子邮件地址在我的应用程序中注册一个用户帐户,我可能会执行 return next(new AlreadyRegistered());。 ,其中AlreadyRegistered构造函数将放置 this.code = 409; //在错误实例上发生冲突属性,因此错误处理中间件将发送该409状态代码。 (使用错误处理中间件,而不是只在正常路由链中处理此正常操作条件错误,就设计而言,错误是有争议的,但希望该示例仍然是示例性的。)

For a concrete example, let's say someone tried to register a user account in my app with an email address that I found already registered in the database, I might do return next(new AlreadyRegistered()); where the AlreadyRegistered constructor function would put a this.code = 409; //Conflict property on the error instance so the error handling middleware would send that 409 status code. (Whether it's better to use error handling middleware vs just dealing with this during the normal routing chain for this "normal operating conditions" error is arguable in terms of design, but hopefully this example is illustrative nonetheless).

仅供参考,我还建议使用 httperrors npm模块具有 statusCode 属性的包装器类。我已经在一些项目中使用了此方法。

FYI I also recommend the httperrors npm module which provides nicely-named wrapper classes with a statusCode property. I have used this to good effect in a few projects.

这篇关于快速错误处理-获取状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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