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

时间:2016-08-05 22:15: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
  }
})

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

Error Logged

当我查看网络标签时,我可以看到响应正文,但出于某种原因,我无法访问这些值!

Network Tab

我是否在某个地方不知不觉地犯了错误?因为我处理来自不同请求的其他错误,但似乎无法解决这个错误。

6 个答案:

答案 0 :(得分:33)

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 => )

编辑:

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

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

EDIT2:

在看了一下this之后,你正在尝试打印。这是一个Javascipt错误对象。然后,Axios会使用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'));

答案 1 :(得分:30)

实施例

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

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

enter image description here

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

答案 2 :(得分:5)

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

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

答案 3 :(得分:2)

我也被困了一段时间。我不会重复太多事情,但我认为增加2美分对其他人有帮助。

上面代码中的error类型为Error。发生的事情是在错误对象上调用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

答案 4 :(得分:2)

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

答案 5 :(得分:0)

您可以使用内联if else语句,如下所示:

public class Employee {

    protected String name;
    protected String surname;
    protected int dateOfBirth;
    protected int experience;

    public Employee(String name, String surname, int dateOfBirth, int experience) {
        this.name = name;
        this.surname = surname;
        this.dateOfBirth = dateOfBirth;
        this.experience = experience;
    }
}

import java.util.ArrayList;
import java.util.List;

public class Company {

    public Company(List<Employee> employeeList) {
        this.employeeList = employeeList;
    }

    public static List<Employee> employeeList = new ArrayList<Employee>();

    Company company = new Company(employeeList);

    for(int i=0; i<employeeList.size(); i++) {
        employeeList.add(new Employee("Mariusz "," Kowalski ",1996,5));
        employeeList.add(new Employee("Krzysztof ", " Nowak ", 1990, 5));
        employeeList.add(new Employee("Robert ", " Klimczyk ", 1985, 10));
    }

    public static void showEmployees() {
        for(int i=0; i<employeeList.size(); i++)
        System.out.println(employeeList.get(i));
    }
}


public class Run {

    public static void main (final String[] args) {

        company.showEmployees();

    }

}