Reputation: 2126
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
?
Upvotes: 1
Views: 3083
Reputation: 74
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
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);
});
Upvotes: 1