我有以下js表达代码:
app.get('/lists2', (req, res) => {
mongo.getDB()
.then(db => db.collection('dogs'))
.then(collection => collection.find().toArray())
.then(array => res.json(success(array)))
// How can I throw in the middle of a promise to trigger express's middleware?
.catch(error => {
throw {message: "database error"};
});
});
app.use(function (err, req, res, next) {
const message = err.message || 'Encountered a server error';
const status = err.status || 500;
res.status(status).json({status, message});
})
我已经编写了一个中间件错误处理程序,因此我可以使用throw
触发API错误响应,问题是我不能扔到then
里面,因为它在异步代码中,是否有任何方法可以避开这个?还是我的错误处理模式不正确?
答案 0 :(得分:1)
您应使用next
(参见doc):
app.get('/lists2', (req, res, next) => {
mongo.getDB()
.then(db => db.collection('dogs'))
.then(collection => collection.find().toArray())
.then(array => res.json(success(array)))
// How can I throw in the middle of a promise to trigger express's middleware?
.catch(error => {
next(new Error("database error"));
});
});
app.use(function (err, req, res, next) {
const message = err.message || 'Encountered a server error';
const status = err.status || 500;
res.status(status).json({status, message});
})