Writing the backend API for my app I've encountered countless examples of people using both forms of handling errors in their endpoint functions, as presented below:
Option 1:
export const deleteProject = asyncHandler(async(req, res) => {
const project = await Project.findByIdAndDelete(req.params.id);
if(project) {
res.status(204).send();
} else {
res.status(404).json({message: "Project not found"});
throw new Error('Project not found');
}
});
Option 2:
export const deleteBoard = asyncHandler(async(req, res) => {
try {
await Board.findByIdAndDelete(req.params.id);
res.status(204).send();
} catch(err) {
res.status(404).json({message: "Board not found"});
throw new Error('Board not found');
}
});
To my current understanding, both of those are correct. I wanted to ask - is one of them preferable because of reasons I might not be aware of?