简体   繁体   中英

How I can catch PHP response error with Axios

I want to catch PHP response errors with Axios.

I have a simple PHP code like this to try to send error to my js file:

header('Content-type: application/json; charset=utf-8');
$test = array (
    'error' => 'test error!'
);  
echo json_encode($test);
die();

And my js with axios like this:

axios({
      method: 'post',
      responseType: 'json',
      url: 'test.php'
      data: '1234'
    })
    .then((response) => {
      if ( response.data.error ) {
        console.log(response.data.error) // I show error here            
      }
      else {            
        console.log(response.data);            
      }
    })
    .catch((error) => {          
      console.log (error); // it's possible to show error here?
    }
)

I can't show error inside catch I think because I made echo json_encode and Axios can not differenciate between error and normal response.

Is there some way to catch errors inside catch ?

If you want to get the error in your catch block, your PHP script must return a HTTP status code other than 2xx Success with error response.

So in your PHP script you should add a HTTP status code. Example: How to send HTTP response code

Because axios only treat a response as an error and pass it to the catch block, when it gets a HTTP status code that not in 2xx Success List

Example from axios:

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
});

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