Axios 422 error

I have an action making a POST request to the server in order to update a user's password, but I'm unable to handle the error in the chained catch block. return axios({ method: 'post', data: {...

Axios is probably parsing the response. I access the error like this in my code:

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

From the docs:

The response for a request contains the following information.

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

So the catch(error => ) is actually just catch(response => )

EDIT:

I still dont understand why logging the error returns that stack message. I tried logging it like this. And then you can actually see that it is an object.

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

EDIT2:

After some more looking around 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'));

We have a project that uses axios@0.14.0 (upgrading to 0.15.3 did not resolve the issue) in many parts of the application. In all of the other parts of the app, we’re able to .catch() 422 response codes. Recently we noticed that 1 request is resolving a promise that gets a 422 response. In all other parts of our application, a 422 causes axios promises to be rejected.

export function addTool(name: string): Thunk {
  return (dispatch, getState) => {
    Axios
      .post<Tool>(API.current.toolsPath, { name })
      .then(resp => {
        if (resp instanceof Error) { throw resp; }
        success("Tool has been saved.", "Success");
        dispatch(addToolOk(resp.data));
      })
      .catch((e: Error) => {
        dispatch(addToolNo(e));
        error(prettyPrintApiErrors(e));
      });
  };
}
if (resp instanceof Error) { throw resp; }

Which works fine, but I’m still confused as to why this particular 422 is resolved (rather than rejected). We also have some interceptors in use, but they haven’t cause any issues for the other requests we make.

Are there any circumstances in that would cause axios to resolve a 422 rather than reject it? Please let me know if you need any other information.

Cover image for Ajax requests with Laravel and Axios - 422 and 419 errors

Irina

Recently I started integrating a bootstrap template with the Laravel backend. And one thing that made me suffer a lot is the ajax backend validation.
Two errors often occur when you handle ajax requests with Laravel: 419 and 422.

The 419 code corresponds to the absence of the csrf token.

To tackle this issue, simply put this into your head:

<meta name="csrf-token" content="{{ csrf_token() }}" />

Enter fullscreen mode

Exit fullscreen mode

And pass it with every request you make to Laravel. (For routes in web.php file)
If you use axios, you can either add it to your global axios config:

axios.defaults.headers = {
  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},

Enter fullscreen mode

Exit fullscreen mode

Or specify when you create an axios instance:

const instance = axios.create({
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
  },
});

Enter fullscreen mode

Exit fullscreen mode

What about 422 Unprocessable Entity?

This error occurs when your backend validation fails.
If you let Laravel refresh your page after POST request, you get errors in @errors directive and stuff, but usually, you want to handle it via ajax either because you care about user experience, or you use a frontend framework such as React or Vue. Or even both.

Here’s how you can tackle the latter issue with axios.

Suppose you validate your form with an email and password input fields:

$request->validate([
  'email' => 'required|min:4',
  'password' => 'required|min:9'
]);

Enter fullscreen mode

Exit fullscreen mode

As axios is a Promise-based library, you can catch errors in catch blocks. However, the problem is that even if you add a catch block after your then,
it won’t help you to get the information about the error in your browser. When you try to log it, you probably get something like this instead of a neat json with errors:

422 log error

Fortunately, the solution is simple. When you access the error data, use error.response instead of error in your catch block, this way:

axios
  .post(endpoint, body, headers)
  .then(response => {
    // Do fancy stuff
  })
  .catch(error => {
    console.log(error.reponse); // logs an object to the console

    // Do something with error data
  });

Enter fullscreen mode

Exit fullscreen mode

Here, error.response is an object with several useful properties such as status, statusText, and data. The latter is what we’re looking for.
There you can find a message property with a general description, and errors object with detailed validation errors.
In the error.response.data.errors object, the keys are the input names, and the values are arrays(!) of strings that describe errors.

Now let’s make a step further, and use some fancy features provided by axios.
Axios gives us an ability to add interceptors to our requests and responses. It allows us to modify requests and responses consistently and stick to the DRY principle.

If you’re not familiar with the concept of interceptors, you can think of it as follows:

  • For requests they modify your request data before sending it to the server,
  • For responses they modify the response before all your then and catch blocks.

If you want to learn more, check out the axios docs on this topic.

Using interceptors, we can add an extra layer:

instance.interceptors.response.use(
  response => response,
  error => Promise.reject(error.response)
);

Enter fullscreen mode

Exit fullscreen mode

Notice that we’re forwarding both the normal response and the error.

And basically, that’s it!

Понравилась статья? Поделить с друзьями:
  • Awk line 1 syntax error at or near
  • Awesome cannot open display error 5
  • Awe 2221 whirlpool коды ошибок
  • Awe 2215 whirlpool ошибки
  • Awd ошибка на инфинити qx60