繁体   English   中英

Node.js表达下一个错误处理程序

[英]Node.js express next error handler

我的代码看起来像这样

app.get('/', function(req, res, next) {
    if (id==8) {
        res.send('0e');
    } else {
        next();
    }
});

app.use(function(err, req, res, next){
  res.send(500, '<h1>Oops! what happened?</h1>');
});

所以。 next()函数称为消息 发生的事情应该出现在屏幕上,但是出现一条消息“ Cannot GET /”

您可以使用未捕获的异常内置的node.js,只需将这段代码放入server.js中

process.on('uncaughtException', function(err) {
   console.log('Caught exception: ' + err);    
   //you can also email this error
});

或点击此链接

http://masashi-k.blogspot.com/2012/12/express3-global-error-handling-domain.html

仅当使用Error对象调用next() ,才会调用错误处理程序。

因此,要触发错误处理程序,您必须执行以下操作:

app.get('/', function(req, res, next) {
    if (id==8) {
        res.send('0e');
    } else {
        next(new Error('Fake error occurred'));
    }
});

app.use(function(err, req, res, next){
  res.send(500, '<h1>Oops! what happened?</h1>');
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM