【发布时间】:2018-12-20 14:57:53
【问题描述】:
假设我有这样的功能 -
doSomeOperation = async () => {
try {
let result = await DoSomething.mightCauseException();
if (result.invalidState) {
throw new Error("Invalid State error");
}
return result;
} catch (error) {
ExceptionLogger.log(error);
throw new Error("Error performing operation");
}
};
这里的DoSomething.mightCauseException 是一个可能导致异常的异步调用,我使用try..catch 来处理它。但是使用得到的结果,我可能会决定我需要告诉doSomeOperation的调用者操作由于某种原因而失败。
在上面的函数中,我抛出的Error 被catch 块捕获,只有一个通用的Error 被抛出给doSomeOperation 的调用者。
doSomeOperation 的调用者可能正在做这样的事情 -
doSomeOperation()
.then((result) => console.log("Success"))
.catch((error) => console.log("Failed", error.message))
我的自定义错误永远不会出现在这里。
在构建 Express 应用时可以使用此模式。路由处理程序会调用一些可能希望以不同方式失败的函数,并让客户端知道失败的原因。
我想知道如何做到这一点?这里还有其他模式可以遵循吗?谢谢!
【问题讨论】:
-
从您的
mightCauseException中投掷。这将冒泡到您的catch块中并被扔到那里。
标签: javascript error-handling async-await