如何在不使用 axios 使函数崩溃的情况下处理错误?

How to handle error without crashing function with axios?

所以问题是,在某些函数中我想调用 getRecord 函数。它正在使用 axios 发出请求。有时请求可能会失败,所以我想在不崩溃我的函数的情况下处理错误,我正在调用 getRecord.

我这样调用 getRecord:

  const res = await getRecord(eventData)
  console.log('handleReadyToRemoveCalls -> res', res)

这里是 getRecord 函数

const getRecord = ({ extTrackingId, targetId }) => {
  console.log('getRecord -> executed')
  const apiConfig = require('../config')

  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url: `https://cloudpbx.beeline.ru/apis/portal/v2/records/${extTrackingId}/${targetId}/download`,
      responseType: 'stream',
      headers: {
        'X-MPBX-API-AUTH-TOKEN': `${apiConfig.token}`,
      },
    })
      .then((response) => {
        console.log('getRecordsReference -> response', response)
        resolve(response)
      })
      .catch((err) => {
        console.log('getRecordsReference -> err', err)
        reject(err)
      })
  })
}

使用这种方法,当 axios 请求失败时,我突然崩溃了。我做错了什么?

您正在拒绝 catch 区块中的承诺:

.catch((err) => {
     reject(err)
})

因此您传播了错误。如果您希望该函数不会失败,只需 return 一些不是空数组之类的错误。例如:

.catch((err) => {
     resolve([])
})

一个另一种方法来处理这个问题是像你一样拒绝并用这样的try catch来捕获更高的错误:

try {
  const res = await getRecord(eventData)
} catch(err){
  // do whatever you want in case of an error
}

用 try catch 环绕。

try{
  const res = await getRecord(eventData)
}catch(err){
//say dispatch a function and say please try again in UI
}

在你承诺你拒绝错误。该错误需要在您调用该函数的块中处理。