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

How to catch and handle error response 422 with 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
  }
})

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

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

我是不是不知不觉哪里弄错了?因为我可以很好地处理来自不同请求的其他错误,但似乎无法解决这个问题。

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

来自文档:

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

{
  // `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: {}
}

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

编辑:

我仍然不明白为什么记录堆栈消息的错误 returns。我试过这样记录它。然后你就可以实际看到它是一个对象。

console.log('errorType', typeof error);
console.log('error', Object.assign({}, error));

编辑 2:

再四处看看后 this is what you are trying to print. Which is a Javascipt error object. Axios then enhances this error with the config, code and reponse like this

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

我也被这个难住了一段时间。我不会过多地重复事情,但我认为添加我的 2 美分会对其他人有所帮助。

上面代码中的errorError类型。发生的事情是在错误对象上调用了 toString 方法,因为您正试图将某些内容打印到控制台。这是隐含的,是写入控制台的结果。如果你看错误对象上toString的代码。

Error.prototype.toString = function() {
  'use strict';

  var obj = Object(this);
  if (obj !== this) {
    throw new TypeError();
  }

  var name = this.name;
  name = (name === undefined) ? 'Error' : String(name);

  var msg = this.message;
  msg = (msg === undefined) ? '' : String(msg);

  if (name === '') {
    return msg;
  }
  if (msg === '') {
    return name;
  }

  return name + ': ' + msg;
};

所以你可以在上面看到它使用内部结构来构建要输出到控制台的字符串。

mozilla 上有很棒的docs

您可以像这样使用内联 if else 语句:

.catch(error => {
    dispatch({
        type: authActions.AUTH_PROCESS_ERROR,
        error: error.response ? error.response.data.code.toString() : 'Something went wrong, please try again.'
    }); 
});

例子

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

检查响应的错误对象,它将包含您要查找的对象,因此您可以执行 error.response.status

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

这是处理 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);
});

来源 url https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253

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

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

唯一对我有帮助的是:

axios.put('/api/settings', settings, {
  validateStatus: status => status >= 200 && status < 300 || status === 422
})

我建议通过 Axios 拦截器处理错误,针对每种情况单独处理:

// interceptor to catch errors
const errorInterceptor = (error) => {
  // check if it's a server error
  if (!error.response) {
    console.log(' API | Network/Server error')
    return Promise.reject(error)
  }

  // all the error responses
  switch (error.response.status) {
    case 400:
      console.error(error.response.status, error.message)
      console.log(' API | Nothing to display', 'Data Not Found')
      break

    case 401: // authentication error, logout the user
      console.log(' API | Please login again', 'Session Expired')
      localStorage.removeItem('user')
      break

    case 403:
      console.error(error.response.status, error.message)
      console.log(' API | Access denied', 'Data Not Found')
      break

    case 404:
      console.error(error.response.status, error.message)
      console.log(' API | Dataset not found', 'Data Not Found')
      break

    case 422:
      console.error(error.response.status, error.message, error.response.data.detail)
      console.log(' API | Validation error', 'Unprocessable Content')
      break

    default:
      console.error(error.response.status, error.message)
  }
  return Promise.reject(error)
}