[英]How setup Node.js error handling?
I have node 7.8.0 and I have read Node.js Best Practice Exception Handling 我有节点7.8.0,并且已经阅读了Node.js最佳实践异常处理
Still I can't seem to understand error handling in node.js. 我仍然似乎无法理解node.js中的错误处理。
For my http
I have 对于我的
http
server.on('error', () => console.log('Here I should be replacing
the Error console.'));
For 404
I have this code 对于
404
我有这个代码
app.use((req, res, next) => {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res) => {
res.status(err.status);
res.render('error');
});
404 is being caught, it creates the Error object and then it's handled by rendering the error view correctly as I want. 404被捕获,它创建Error对象,然后通过根据需要正确呈现错误视图进行处理。 But it also throws error log to my console and I have no idea where that is coming from and how to stop it.
但这也会向我的控制台抛出错误日志,我不知道它来自哪里以及如何停止它。
I would like to use my own error handling and never actually write errors like 404 into the console. 我想使用自己的错误处理方式,并且从不实际将404之类的错误写入控制台。
Codes that I tried and don't seem to work. 我尝试过但似乎不起作用的代码。
var server = http.createServer(app);
const onError = () => console.log('Here I should be replacing the Error console.');
server.on('error', onError);
server.on('uncaughtException', onError);
process.on('uncaughtException', onError);
This is due to expressjs. 这是由于expressjs。 Expressjs if the env is not equal to the test , the all errors writes to the console.
Expressjs如果env不等于test ,则所有错误都会写入控制台。
function logerror(err) {
if (this.get('env') !== 'test') console.error(err.stack || err.toString());
}
Also http.Server does not have an event named error . 另外,http.Server没有名为error的事件。
I'm not sure how it can render the error view, given that error handlers require 4 arguments while you're passing it only 3. This is how Express can distinguish error handlers from normal route handlers (documented here ). 我不确定它如何呈现错误视图,因为错误处理程序仅在传递3个参数时需要4个参数,这就是Express可以将错误处理程序与常规路由处理程序区分开的方式( 此处记录 )。
Try this instead: 尝试以下方法:
app.use((err, req, res, next) => {
res.status(err.status);
res.render('error');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.