1

我是 TypeScript/JavaScript 和 Node.js 的新手,来自 Java/Scala 背景。
我正在编写一个简单的脚本TypeScript来收集一些数据并将它们作为 HTTP POST 请求发送到使用axios.

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. "catch" AxiosErrorafter 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

4

1 回答 1

1

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)
于 2020-08-26T16:17:27.073 回答