Node, Express, domains, uncaught exceptions - still lost

对着背影说爱祢 提交于 2019-12-05 02:50:26
Waqas Ahmed

You can use connect-domain.

The problem is that the exception happens during Connect's routing, which has both a try/catch block around its execution, as well as a default error handler which prints out stack trace details when running in a non-production mode. Since the exception is handled inside of Express, it never reaches your outer layer for the domains to handle.

Here is an example why to use connect-domain package instead of domain.

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

var express = require('express');
var connectDomain = require('connect-domain');

var app = express();
app.use(connectDomain());
app.get('/testing', function() {
    app.nonExistent.call(); // this throws an error
});

app.use(function(err, req, res, next) {
    res.end(err.message); // this catches the error!!
});

var server = app.listen(8000, function() {
    console.log('Listening on port %d', server.address().port);
});

This happens because Express handles by itself the errors that may appear and in this way it simplifies your work. See Express Guide for error handling. You should use the structure below to handle the errors that may appear:

app.use(function(err, req, res, next){
    console.error(err.stack);
    res.send(500, 'Something broke!');
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!