如何使用Redux/Axios捕获和处理错误响应422?

Phi*_*eng 43 javascript reactjs redux axios

我有一个动作POST向服务器发出请求以更新用户的密码,但我无法处理链接的catch块中的错误.

return axios({
  method: 'post',
  data: {
    password: currentPassword,
    new_password: newPassword
  },
  url: `path/to/endpoint`
})
.then(response => {
  dispatch(PasswordUpdateSuccess(response))
})
.catch(error => {
  console.log('ERROR', error)
  switch (error.type) {
    case 'password_invalid':
      dispatch(PasswordUpdateFailure('Incorrect current password'))
      break
    case 'invalid_attributes':
      dispatch(PasswordUpdateFailure('Fields must not be blank'))
      break
  }
})
Run Code Online (Sandbox Code Playgroud)

当我记录错误时,这就是我所看到的:

记录错误

当我检查网络选项卡时,我可以看到响应正文,但由于某种原因我无法访问这些值!

网络选项卡

我在某个地方不知不觉地犯了错误吗?因为我正在处理来自不同请求的其他错误,但似乎无法正常工作.

Jer*_*enk 39

Axios可能正在解析响应.我在我的代码中访问这样的错误:

axios({
  method: 'post',
  responseType: 'json',
  url: `${SERVER_URL}/token`,
  data: {
    idToken,
    userEmail
  }
})
 .then(response => {
   dispatch(something(response));
 })
 .catch(error => {
   dispatch({ type: AUTH_FAILED });
   dispatch({ type: ERROR, payload: error.data.error.message });
 });
Run Code Online (Sandbox Code Playgroud)

来自文档:

请求的响应包含以下信息.

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {}
}
Run Code Online (Sandbox Code Playgroud)

所以catch(error => )实际上只是catch(response => )

编辑:

我仍然不明白为什么记录错误会返回该堆栈消息.我试着像这样记录它.然后你可以看到它是一个物体.

console.log('errorType', typeof error);
console.log('error', Object.assign({}, error));
Run Code Online (Sandbox Code Playgroud)

EDIT2:

经过一番调查之后,就是您要打印的内容.这是一个Javascipt错误对象.爱可信则增强了这种错误与配置,代码和效应初探喜欢这样.

console.log('error', error);
console.log('errorType', typeof error);
console.log('error', Object.assign({}, error));
console.log('getOwnPropertyNames', Object.getOwnPropertyNames(error));
console.log('stackProperty', Object.getOwnPropertyDescriptor(error, 'stack'));
console.log('messageProperty', Object.getOwnPropertyDescriptor(error, 'message'));
console.log('stackEnumerable', error.propertyIsEnumerable('stack'));
console.log('messageEnumerable', error.propertyIsEnumerable('message'));
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的详细回复,我查看了帮助的存储库代码.最终我记录了对象,并能够看到响应对象并处理数据.附加代码:`let e = {... error}``switch(e.response.data.type)` (4认同)

Ste*_*ett 38

getUserList() {
    return axios.get('/users')
      .then(response => response.data)
      .catch(error => {
        if (error.response) {
          console.log(error.response);
        }
      });
  }
Run Code Online (Sandbox Code Playgroud)

检查错误对象的响应,它将包含您正在查找的对象,以便您可以执行此操作 error.response.status

在此输入图像描述

https://github.com/mzabriskie/axios#handling-errors

  • 正是我需要的!谢谢 (3认同)
  • 是的!访问 err.response 得到我需要的东西,谢谢! (2认同)

Sup*_*ion 6

这是处理error对象的正确方法:

axios.put(this.apiBaseEndpoint + '/' + id, input)
.then((response) => {
    // Success
})
.catch((error) => {
    // 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);
});
Run Code Online (Sandbox Code Playgroud)

原始网址https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253


小智 5

axios.post('http://localhost:8000/api/auth/register', {
    username : 'test'
}).then(result => {
    console.log(result.data)
}).catch(err => {
    console.log(err.response.data)
})
Run Code Online (Sandbox Code Playgroud)

添加捕获错误响应 ==> err.response.data