如何解决如何改善我对此承诺链的错误处理?
我是TypeScript / JavaScript和Node.js的新手,来自Java / Scala背景。
我正在TypeScript
中编写一个简单的脚本,以收集一些数据,并使用axios
将它们作为HTTP POST请求发送到服务器。
makePromiseToGetA()
.then((a: A) => makePromiseToGetB(a))
.then((b: B) => sendHttpRequestAxios(b))
.then((resp: AxiosResponse) => outputResponse(resp))
.catch((err: Error) => handleError(err))
现在,我想改善错误处理。具体来说,除了通用错误处理(功能AxiosError
)之外,我还想使用函数handleAxiosError(ae: AxiosError)
处理handleError
现在,我看到两个选择可以做到这一点:
-
像这样修改
handleError
函数:// pseudocode because I don't know how to code this in TypeScript function handleError(err: Error): void { if (err instanceof AxiosError) { handleAxiosError(err as AxiosError); } ... // handle Error }
在 -
“捕获”
sendHttpRequestAxios
,处理该错误,然后将其重新抛出:makePromiseToGetA() .then((a: A) => makePromiseToGetB(a)) .then((b: B) => sendHttpRequestAxios(b).catch((ae: AxiosError) => {handleAxiosError(ae); throw ae;})) .then((resp: AxiosResponse) => outputResponse(resp)) .catch((err: Error) => handleError(err))
AxiosError
之后除了使用AxiosError
处理一般错误之外,您如何建议使用handleAxiosError
处理{1}?{1>}?
解决方法
如果您通常希望以不同于其他错误的方式处理Traceback (most recent call last):
File "C:\-------",line 37,in <module>
result = text.generate(length)
File "C:\-------",line 30,in generate
newWord = r.choice(self.graph[orginalState])
KeyError: ('society','for','s')
实例,那么#1对我来说似乎是一个合理的解决方案。 #2的问题在于,您将最终两次处理该错误:一次是在特定于Axios的拒绝处理程序中,然后是在AxiosError
中。
如果您不喜欢这种handleError
方法(在instanceof
或最后的拒绝处理程序中),则可以使用嵌套:
handleError
这利用了Axios部分是链中最后一个非拒绝部分这一事实。因此,您可以通过makePromiseToGetA()
.then((a: A) => makePromiseToGetB(a))
.then((b: B) =>
sendHttpRequestAxios(b)
.then((resp: AxiosResponse) => outputResponse(resp))
.catch((err: AxiosError) => handleAxiosError(ae))
)
.catch((err: Error) => handleError(err))
进行处理,将拒绝转化为实现-但没有任何东西可以使用结果实现,因此您很好。但是,如果发生 other 错误,您最终将进入最终拒绝处理程序。
旁注:这只是一个示例,您的实际代码可能更复杂(尽管拒绝处理程序可能不是),但是当将实现值或拒绝原因作为参数传递给函数时,则不需要包装箭头功能:
handleAxiosError
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。