如何使用Axios捕捉PHP响应错误



我想用Axios捕捉PHP响应错误。

我有一个像这样的简单PHP代码,试图将错误发送到我的js文件:

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

我的js和axios是这样的:

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

我想我不能在catch中显示错误,因为我制作了echo json_encode,Axios无法区分错误和正常响应。

有什么方法可以捕捉catch内部的错误吗?

如果你想在catch块中得到错误,你的PHP脚本必须返回一个HTTP状态码,而不是2xx成功并返回错误响应。

因此,在您的PHP脚本中,您应该添加一个HTTP状态代码。示例:如何发送HTTP响应代码

因为axios只将响应视为错误并将其传递给catch块,当它获得不在2xx成功列表中的HTTP状态代码时

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

最新更新