使用try/catch on方法



我对多个对象方法使用多个相同的try/catch测试。因此,我想创建try/catch方法来引用我的代码,但不会返回错误。

例如:

@autobind
async forgottenPassword(req, res) {
return this.callService(
res,
async () => await companyService.forgottenPassword(req.body.formData)
);
}
callService(res, func) {
try {
func();
} catch (error) {
res.statusMessage = error.message;
res.status(error.statusCode);
} finally {
res.end();
}
}

我的catch从未被调用:/

有人知道我犯了错误吗?

谢谢!

您需要将callService设为async,并在那里使用await

@autobind
async forgottenPassword(req, res) {
return this.callService(
res,
async () => await companyService.forgottenPassword(req.body.formData)
);
}
async callService(res, func) {
try {
await func();
} catch (error) {
res.statusMessage = error.message;
res.status(error.statusCode);
} finally {
res.end();
}
}

最新更新