Search code examples
javascriptaxioses6-promise

How to handle error without crashing function with axios?


So the problem is, that in some function i want to call getRecord function. It's making request with axios. Some times request can be faild, so i want to handle the error without crashing my function, where i'm calling getRecord.

I'm calling getRecord like this:

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

Here is the getRecord function

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)
      })
  })
}

With this approach i'm suddenly for me getting crashes, when request with axios fails. What's i'm doing wrong?


Solution

  • You are rejecting the promise in the catch block:

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

    Thus your propagate the error. If you want the function not to fail just return something that is not an error like an empty array. For instance:

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

    One other way to handle this is to reject as you do and to catch the error higher with a try catch like this:

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