网站搜索

如何编写 TypeScript 异步 Axios?以及如何使用 try/catch


我正在尝试弄清楚编写 TypeScript 异步 Axios 请求的最佳方式。如果每个函数都应该有自己的 try/catch 块,该怎么办?如果是,应该如何为函数结果指定类型?

使用 try/catch 块时,类型是:Promise<ExpectedType | undefined>。没有 try/catch 块时,类型是 Promise<ExpectedType>。

这是例子:

async function v1(): Promise<ExpectedType> {
  const response = await axios.get('https://...')
  return response.data
}

async function v1Copy(): Promise<ExpectedType> {
  const response = await axios.get('https://...')
  return response.data
}

async function v2(): Promise<ExpectedType | undefined> {
  try {
    // I could use object destructuring for 'data' but ignore this for now
    const response = await axios.get('https://...')
    return response.data
  } catch (e) {
    // how to handle this safely
    const error = e as AxiosError | Error
    if (error instanceof AxiosError) {
      if (error.response) {
        console.error(`axios error: ${error.response.status} ${error.response.statusText}`)
      } else {
        console.error(`axios error: ${error.message}`)
      }
    } else {
      console.error(`generic error: ${error.message}`)
    }
  }
}

现在,当我需要在代码的其他部分使用 v1/v1Copy 时,我必须将其包装在 try catch/catch 块中。这是显而易见的。

做这个的最好方法是什么?

...
try {
  const v1Result = await v1()
  const v1CopyResult = await v1Copy()
  // use v1Result and v1CopyResult
} catch(e) {}

对

...
const v2Result = await v2()
if (typeof v2Result !== 'undefined') {
  // here should be a typeguard, right?
  // use v2Result
}

在同一个 try/catch 块中使用 v1 和 v1Copy 可以吗?谢谢……我正在尝试找到处理这个问题的最佳方法,并理解原因。

答案#1

我认为最好的方法是将每个函数都包裹在它自己的 try/catch 块中,这样即使一个 promise 被拒绝,整个代码也不会崩溃。