I have a question about catching user error in async and wait.
Let say I have a route that only fetches for a single user.
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
});
});
});
I have a controller that fetches the request. 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;
}
}
So no matter what happens either I get a null or a single record. It is still a success. In promises, I can reject null, so it will show up in the catch block in the route. Now that with async and await. How can I achieve the same making the null in the error block?
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);
});
});
}