Javascript 如何在不破坏axios功能的情况下处理错误?

Javascript 如何在不破坏axios功能的情况下处理错误?,javascript,axios,es6-promise,Javascript,Axios,Es6 Promise,所以问题是,在某些函数中,我想调用getRecord函数。它正在向axios发出请求。有时请求可能会失败,因此我希望在不破坏函数的情况下处理错误,我正在调用getRecord. 我这样给getRecord打电话: const res = await getRecord(eventData) console.log('handleReadyToRemoveCalls -> res', res) try { const res = await getRecord(eventDat

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

我这样给getRecord打电话:

  const res = await getRecord(eventData)
  console.log('handleReadyToRemoveCalls -> res', res)
try {
  const res = await getRecord(eventData)
} catch(err){
  // do whatever you want in case of an error
}
下面是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)
})
因此,您将传播错误。如果希望函数不失败,只需返回非错误的内容,如空数组。例如:

.catch((err) => {
     resolve([])
})
处理此问题的另一种方法是按您所做的方式拒绝错误,并使用如下的try-catch捕捉更高的错误:

  const res = await getRecord(eventData)
  console.log('handleReadyToRemoveCalls -> res', res)
try {
  const res = await getRecord(eventData)
} catch(err){
  // do whatever you want in case of an error
}

您拒绝了
catch
块中的承诺:

.catch((err) => {
     reject(err)
})
因此,您将传播错误。如果希望函数不失败,只需返回非错误的内容,如空数组。例如:

.catch((err) => {
     resolve([])
})
处理此问题的另一种方法是按您所做的方式拒绝错误,并使用如下的try-catch捕捉更高的错误:

  const res = await getRecord(eventData)
  console.log('handleReadyToRemoveCalls -> res', res)
try {
  const res = await getRecord(eventData)
} catch(err){
  // do whatever you want in case of an error
}

围着试抓

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

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

用try-catch环绕

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

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

需要捕获可能的错误,并使用
try{}catch{}
语句相应地处理它。您可以从我的快速谷歌搜索中查询,您需要捕获可能的错误,并使用
try{}catch{}
语句相应地处理它。你可以通过我的快速谷歌搜索进行咨询