我有一个具有典型快速配置的 server.js
,以及一个单独的 routes.js
来处理路由。
server.js
...
app.use('/', router);
app.use((err, req, res, next) => {
console.error(err);
res.status(500).render('error-server', {
layout: 'main',
title: 'Server Error'
});
});
...
routes.js
const fetch = require('node-fetch');
router.get('/what', function (req, res) {
throw new Error('BROKEN'); // works, throws the error that is handled in server.js
});
router.get('/test', (req, res) => {
fetch('wrong_url_to_test_error_handling')
.then(checkStatus)
.then(res => res.json())
.then(json => console.log(json));
res.send('Ok');
});
function checkStatus(res) {
if (res.ok) {
return res;
} else {
throw new Error('BROKEN'); // this does not work
}
}
/what
路由可以正确处理错误,但 /test
路由则不能。 checkStatus
函数的 fetch 失败,并且会触发 else 语句,但抛出的错误的处理方式与 /what
路由的错误处理方式不同。这有什么原因吗?
谢谢:)
最佳答案
您将其放入 promise 链中,并且由于没有 .catch
,错误会被吞掉。
这就是它无法到达 Express 错误处理程序的原因。
在这种情况下,您需要通过链接 .catch
将错误转发到 next
函数:
router.get('/test', (req, res, next) => {
fetch('wrong_url_to_test_error_handling')
.then(checkStatus)
.then(res => res.json())
.then(json => {
console.log(json)
res.send('Ok')
})
.catch(next)
})
关于javascript - 为什么 Express 句柄不抛出新错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57872545/