gpt4 book ai didi

node.js - 如何在 Express 中出现未捕获错误后呈现 500 响应?

转载 作者:太空宇宙 更新时间:2023-11-03 23:08:38 25 4
gpt4 key购买 nike

app.get('/', function(req, res) {
doSomethingAsync(function(err) {
throw new Error('some unexpected/uncaught async exception is thrown');
})
})

Possibly unhandled Error: some unexpected/uncaught async exception is thrown
at ...stacktrace...:95:9
From previous event:
at ...stacktrace...:82:6)
at ...stacktrace...:47:6)
at ...stacktrace...:94:18)

我尝试了很多域中间件,但它们都只适用于express 3。我目前使用的是express 4.5,我想知道express是否已更改该域不再工作。

目前,当抛出异常时,响应基本上会挂起,直到超时。

最佳答案

假设您遇到的错误是在路由器或 Controller 内部在收听之前,将其放在应用程序配置的最末尾

app.use(function(err, req, res) {
res.status(err.status || 500);
// if you using view enggine
res.render('error', {
message: err.message,
error: {}
});
// or you can use res.send();
});

您的应用程序将捕获任何未捕获的路由器错误并呈现“错误”页面

顺便说一句,不要忘记在路由器初始化中包含“next”

<小时/>

已编辑

app.get('/', function(req, res, next) {
try {
signin(req.query.username, req.query.password, function(d){
if (d.success) {
req.session.user = d.data;
}
res.end(JSON.stringify(d));
});
} catch(e) {
next(e);
}
}

希望对你有帮助

关于node.js - 如何在 Express 中出现未捕获错误后呈现 500 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25539479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com