devamat
devamat

Reputation: 2503

How to properly handle axios errors and how to get detailed error descriptions?

I have a question about axios and error handling. So this is the method I'm using to handle errors when the user logins from the front end:

    axios.post('http://localhost:3001/login',
        {
            login: user.login,
            password: user.password,
        }
    )
    .then(
        (response) => {
            // code
        },
        (error) => {
            // error handling
        }
    );

This is the second method:

    axios.post('http://localhost:3001/login',
        {
            login: user.login,
            password: user.password,
        }
    )
    .then(
        (response) => {
            // code
        }
    ).catch((error) => {
        // error handling
    });

What is the best approach? Is it the same? When the server is unreachable the error message is the same: "Network Error". Is there any way to get a more detailed error? (For example in the console I get a CORS error)

Upvotes: 2

Views: 7537

Answers (2)

Karthik R
Karthik R

Reputation: 5786

The error can occur at different parts - Request, Response.

Request errors occur when there is no response. Like 404 etc, which has no default response.

Response errors have when API sends custom response to handle errors.

I used to handle this way:

const handleErrorResponse = (error) => {
  let errorResponse;
  if(error.response && error.response.data) {
    // I expect the API to handle error responses in valid format
    errorResponse = error.response.data;
    // JSON stringify if you need the json and use it later
  } else if(error.request) {
    // TO Handle the default error response for Network failure or 404 etc.,
    errorResponse = error.request.message || error.request.statusText;
  } else {
    errorResponse = error.message;
  }
  throw new Error(errorResponse);
}

now,

axios.get(/foo/bar)
.then(res => doSOmething())
.catch(err => handleErrorResponse(err))

The I use error handling the error response as string. The same you can use it with axios interceptor should you need.

Upvotes: 8

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11930

This is not valid, then accepts single argument

.then(
        (response) => {
            // code
        },
        (error) => {
            // error handling
        }
    );

Only this's valid

.then(
        (response) => {
            // code
        }
    ).catch((error) => {
        // error handling
    });

Upvotes: -2

Related Questions