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

时间:2018-12-11 17:29:27

标签: javascript php axios

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

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

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

我的带有axios的js是这样的:

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内部的错误?

1 个答案:

答案 0 :(得分:0)

如果要在catch块中获取错误,则PHP脚本必须返回HTTP 2xx Success以外的HTTP状态代码,并带有错误响应。

因此,在您的PHP脚本中,您应该添加HTTP状态代码。示例:How to send HTTP response code

因为axios仅将响应视为错误并将其传递到catch块,当它获得不在2xx Success List中的HTTP状态代码时

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