我正在编写一个中间件,它有一个服务层和一个控制器层,为了向用户发送一个清晰的错误消息,我在服务层捕获任何错误,然后抛出一个新的Error,并带有一个个性化的消息,如下所示:
// services.js
async getOneRecord(id) {
const url = this.url + `/${id}`;
return await axios.get(url).then((res) => res.data);
}
// UserServices.js
async getTaxValue(id) {
try {
const user = await this.getOneRecord(id);
return Number(user.tax) / 100;
} catch (error) {
throw new Error(`User ID not found: ${id}`);
}
}
// UserController.js
static async getUserTax(req, res) {
const { userId } = req.params;
try {
const user = await userServices.getTaxValue(userId);
return res.status(200).json(user);
} catch (error) {
return res.status(404).json(error.message);
}
}
我想知道这是否是正确的处理错误的方法,或者我是否做错了什么。
1条答案
按热度按时间lztngnrs1#
是的,它是正确的,并且与
catch
数据块中的throw
新错误正常。然而,忽略您捕获的
error
并不是一个好习惯。在getTaxValue
中有很多事情可能出错,我认为其中大多数不应该导致“id not found”错误。因此,请非常明确地指出您预期的错误,使用条件测试它,然后重新抛出所有其他未更改的错误。还要设置.cause
of errors。在您的情况下,可能是(来自用户记录端点的handling only 404 errors):