if(err) {
// Handle "Not Found" by responding with a custom error page
if(err.fileNotFound) {
return this.sendErrorMessage('File Does not Exist');
}
// Ignore "No Permission" errors, this controller knows that we don't care
// Propagate all other errors (Express will catch them)
if(!err.noPermission) {
return next(err);
}
}
为了在node 模块和应用中统一平衡、非阻塞的异步控制流,node 采用了错误优先(error-first)的callback 回调形式。这种形式的回调是追溯到 Continuation-Passing Style (CPS)。CPS 中的“continuation function”接受一个函数作为参数,这个参数函数在函数体中其余代码执行完之后运行。这样的方式使得不同的函数能够异步地控制整个应用。
例子,一个标准的错误优先callback例子:
处理错误的方式
如果想让node 应用sutdown停止的话,可以直接throw 抛出异常;
如果正处于一个异步流的阶段,可以把错误propagate 冒泡出来,传递给下一个next callback函数;
参考
The Node.js Way - Understanding Error-First Callbacks