如何改善我对此承诺链的错误处理?

问题描述

我是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

现在,我看到两个选择可以做到这一点:

  1. 像这样修改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
    }
    
  2. AxiosError之后
  3. “捕获” 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 处理{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