javascript - 使用 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
的从未被调用:/
有谁知道我做错了吗?
谢谢 !
解决方案
您需要进行 callServiceasync
并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();
}
}
推荐阅读
- r - 如果它们在指定时间段内具有连续的时间间隔,则合并数据行
- scala - AffinityKeyMapped 不适用于 Ignite 2.4/2.5/2.6 和 Scala
- excel - 如何从只能在 chrome 中查看的网站获取数据
- javascript - 使用 axios.all() 和 axios.spread() “找不到变量”方法错误
- django - 同一对模型的一对一和多对一关系
- r - 将成对数据转换为符合 prefmod 的列顺序
- python - 执行 Selenium Python 自动化脚本时出错
- sql - 转换函数 SQL Server
- three.js - 场景中两个对象之间的三个 js RayCast
- javascript - 下面的代码是异步的吗?