简体   繁体   中英

Code Execution stops after axios 500 internal server error

I'm using axios with trycatch but when the api returns 500 internal server error, the code execution flows to catch but outside the async function code doesn't execute, I don't know why.

Here is my code:

export async function authRequest(router, path='/', data={}, method='get') {

  const authKey = getAuthKey();

  try {
    const request = await axios({
      method,
      url: apiUrl + path,
      headers: {
        'Authorization': "Bearer " + authKey
      },
      data
    });

    return request.data;
  } catch (error) {

    const isLogged = await axios({
      method: 'get',
      url: apiUrl + '/isLoggedUser',
      headers: {
        'Authorization': "Bearer " + authKey
      }
    });

    if (isLogged.data == false) {
      router.push({
        name: 'login'
      })
    } else {
      console.error('Cannot process this request');
      return false;
    }
  }
}

Calling this function:

const req = await authRequest(
    this.$router,
    '/video/play',
  );

console.log('cannot reach to this statment after 500 error in axios request')

As the last console.log statement doesn't execute/reach or any code after when Axios throws 500 internal server error.

Please note that: the problem is with axios 500 internal server that stops further code execution outside the authRequest function.

The Axios request you are making in the catch block should be surrounded by try/catch. Any response other than 2XX will go to catch block(throws error).

For more about this

export async function authRequest(router, path = '/', data = {}, method = 'get') {

  const authKey = getAuthKey();

  try {
    const request = await axios({
      method,
      url: apiUrl + path,
      headers: {
        'Authorization': "Bearer " + authKey
      },
      data
    });

    return request.data;
  } catch (error) {

    try {
      const isLogged = await axios({
        method: 'get',
        url: apiUrl + '/isLoggedUser',
        headers: {
          'Authorization': "Bearer " + authKey
        }
      });

      if (isLogged.data == false) {
        router.push({
          name: 'login'
        })
      }
    } catch (e) {
      console.error('Cannot process this request');
      return false;
    }
  }
}

Can you try by using try/catch when you are calling the authRequest .

try{

    const req = await authRequest(
    this.$router,
    '/video/play',
  );
  console.log('cannot reach to this statment after 500 error in axios request')
}
catch(e){
    console.log('cannot reach to this statment after 500 error in axios request')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM