我是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
}
AxiosError
之后“捕获” 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
进行一般错误处理外,您如何建议使用handleAxiosError
处理handleError
?
最佳答案
如果您通常想以不同的方式处理AxiosError
实例,那么#1对我来说似乎是一个合理的解决方案。 #2的问题是,您将最终两次处理错误:一次在特定于Axios的拒绝处理程序中,然后一次在handleError
中。
如果您不喜欢这种instanceof
方法(在handleError
或最后的拒绝处理程序中),则可以使用嵌套:
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))
这利用了Axios部分是链中最后一个非拒绝部分这一事实。因此,您可以通过handleAxiosError
来处理它,将拒绝转换为实现-但是没有任何东西可以使用结果实现,因此您很好。但是,如果发生其他错误,您将进入最终拒绝处理程序。旁注:这只是一个示例,您的实际代码可能更复杂(尽管拒绝处理程序可能不是),但是当将实现值或拒绝原因作为参数传递给函数时,不需要包装箭头函数:
makePromiseToGetA()
.then(makePromiseToGetB)
.then((b: B) =>
sendHttpRequestAxios(b)
.then(outputResponse)
.catch(handleAxiosError)
)
.catch(handleError)
关于node.js - 如何改善我对此 promise 链的错误处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63601504/