我想用 async/await 替换 Express 路由中的 promise 链。这使得代码干净且更具可读性。首先看我的代码。
我以前经历过:
app.post('/search', (req,res) => {
sendRequest(req.body).then( searchDetails => {
res.send(searchDetails);
}).catch( error => {
res.status(404).send(error)
});
});
当前代码:
app.post('/search', asyncMiddleware(async (req,res) => {
const result = await sendRequest(req.body);
res.send(result);
}));
这看起来是异步中间件:
const asyncMiddleware = checkedFunction => (req, res) => {
Promise
.resolve(
checkedFunction(req, res)
)
.catch( error => {
res.status(400).send(error)
});
};
当我的路由包含多个错误状态时,问题就开始了。
app.delete('/delete/:id', authenticate, (req, res) => {
const id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
User.findOneAndDelete({
_id: id,
_user: req.user._id
}).then((todo) => {
if (!todo) {
return res.status(404).send();
}
res.send({todo});
}).catch((e) => {
res.status(400).send();
});
});
如何使 asyncMiddleware 根据错误返回状态?
最佳答案
asyncMiddleware
此处检查是否发生任何错误或由 checkedFunction
(即快速路由处理程序)故意抛出的错误。如果您想对 asyncMiddleware
说些什么,您需要像对 /search
所做的那样用它包装您的路由处理程序,然后您需要抛出涉及以下内容的特定错误/对象:您的错误信息:
app.delete('/delete/:id', authenticate, asyncMiddleware(async (req, res) => {
const id = req.params.id;
if (!ObjectID.isValid(id)) {
throw {
status: 404,
message: 'id not valid'
}
}
try {
const todo = await User.findOneAndDelete({
_id: id,
_user: req.user._id
});
if (!todo) {
throw {
status: 404,
message: 'todo not found'
}
}
res.send({todo});
} catch (e) {
throw {
status: 400,
message: 'mongodb error'
}
}
}));
然后 asyncMiddleware 可以发送状态作为响应
const asyncMiddleware = checkedFunction => (req, res) => {
Promise
.resolve(
checkedFunction(req, res)
)
.catch( error => {
res.status(error.status).send(error.message)
});
};
您可以创建内置的 Error
对象而不是自定义对象来跟踪错误调用堆栈,但我认为您不需要在这里。
关于javascript - Express 异步/等待错误处理程序中的动态响应状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54689921/