Node.js + Express.js应用程序的错误处理原理? [英] Error handling principles for Node.js + Express.js applications?

查看:107
本文介绍了Node.js + Express.js应用程序的错误处理原理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎错误报告/处理在Node.js + Express.js 应用程序与其他框架相比。我正确理解,它的工作原理如下?

It seems like error reporting/handling is done differently in Node.js+Express.js applications compared to other frameworks. Am I correct in understanding that it works as follows?

A) 通过接收错误作为参数检测错误你的回调函数。例如:

A) Detect errors by receiving them as parameters to your callback functions. For example:

doSomethingAndRunCallback(function(err) { 
    if(err) { … }
});

B) 报告 MIDDLEWARE中的​​错误调用next(err)。示例:

B) Report errors in MIDDLEWARE by calling next(err). Example:

handleRequest(req, res, next) {
    // An error occurs…
    next(err);
}

C) > ROUTES中的错误通过抛出错误。示例:

C) Report errors in ROUTES by throwing the error. Example:

app.get('/home', function(req, res) {
    // An error occurs
    throw err;
});

D) 通过配置您的自己的错误处理程序通过app.error()或使用通用的连接错误处理程序。示例:

D) Handle errors by configuring your own error handler via app.error() or use the generic Connect error handler. Example:

app.error(function(err, req, res, next) {
    console.error(err);
    res.send('Fail Whale, yo.');
});

这四个原则是Node.js + Express.js应用程序中所有错误处理/报告的基础?

Are these four principles the basis for all error handling/reporting in Node.js+Express.js applications?

推荐答案

Node.js中的错误处理通常是格式A)。大多数回调函数返回一个错误对象作为第一个参数或 null

Error handling in Node.js is generally of the format A). Most callbacks return an error object as the first argument or null.

Express.js使用中间件和中间件语法使用B)和E)(如下所述)。

Express.js uses middleware and the middleware syntax uses B) and E) (mentioned below).

C)如果您问我是不好的做法。

C) is bad practice if you ask me.

app.get('/home', function(req, res) {
    // An error occurs
    throw err;
});

您可以轻松地将上述内容重写为

You can easily rewrite the above as

app.get('/home', function(req, res, next) {
    // An error occurs
    next(err);
});

中间件语法在 get 请求中有效

Middleware syntax is valid in a get request.

至于D)


(07:26:37 PM) tjholowaychuk:app.error在3.x中删除

(07:26:37 PM) tjholowaychuk: app.error is removed in 3.x

TJ刚刚确认 app.error 不赞成使用E

TJ just confirmed that app.error is deprecated in favor of E

E)

app.use(function(err, req, res, next) {
  // Only handle `next(err)` calls
});

任何长度为4(4个参数)的中间件都被认为是错误中间件。当一个人调用 next(err) connect,并调用基于错误的中间件。

Any middleware that has a length of 4 (4 arguments) is considered error middleware. When one calls next(err) connect goes and calls error-based middleware.

这篇关于Node.js + Express.js应用程序的错误处理原理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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