Node.js + Express.js 应用的错误处理原则? [英] Error handling principles for Node.js + Express.js applications?
问题描述
似乎在 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) 通过调用 next(err) 报告 MIDDLEWARE 中的错误.示例:
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() 配置您自己的错误处理程序或使用通用的 Connect 错误处理程序来处理错误.示例:
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屋!