我有一个关于在异步和等待中捕获用户错误的问题 .
假设我有一条仅为单个用户提取的路由 .
routes.js
routes.get('/getuserbyid/:id', (req, res) => {
const id = req.params.id;
accountController.getById(id)
.then((result) => {
res.json({
confirmation: 'success',
result: result
});
})
.catch((error) => {
res.json({
confirmation: 'failure',
error: error
});
});
});
我有一个控制器来获取请求 . accountController.js
export const getById = async (id) => {
try {
const user = await users.findOne({ where: {
id: id
}});
if (user === null) {
return 'User does not exist';
}
return user;
} catch (error) {
return error;
}
}
所以无论发生什么,我都会获得空或单个记录 . 它仍然是成功的 . 在promises中,我可以拒绝null,因此它将显示在路径中的catch块中 . 现在用异步和等待 . 如何在错误块中实现相同的null?
export const getById = (id) => {
return new Promise((resolve, reject) => {
users.findOne({ where: {
id: id
}})
.then((result) => {
if (result === null) {
reject('User does not exit');
}
resolve(result);
})
.catch((error) => {
reject(error);
});
});
}
3 回答
首先,避免使用Promise反模式 . 你有一个返回Promise的函数,不需要在_140726中包装它 .
然后你的功能可能如下所示:
和async / await版本是
async
函数始终返回Promise
.在
async
函数中使用throw
构造会拒绝返回的Promise
.考虑
异步方法中的
try
块处理同步和异步错误 .考虑
要记住的一个关键点是,如果您忘记了拒绝使用它们的承诺,则不会捕获异步错误 . 这是忘记
.then
内部的return
或.catch
回调的类比如果你的值变空,你可以抛出异常 .