4
votes

As I mentioned above my Axios on Nuxt.js is not catch error properly

I need to know the error, so I can prompt to let the user know their input is not correct but it only console.log the error code status not the message from my API

this is my code

await axios
  .post(
    "API LINK",
    {
      email: user.email,
      password: "123456",
      name: user.name,
      dob: user.dob ?? null,
      gender: user.gender ?? null,
      profileImage: imageUrl ?? user.profileImage,
      userType: user.userType
    }
  )
  .then(res => {
    console.log("success");
    console.log(res);
  })
  .catch(err => {
    console.log('fail');
    console.log(err)
  })

This is what log on a chrome console

error
add.vue?104b:181 Error: Request failed with status code 400
    at createError (createError.js?2d83:16)
    at settle (settle.js?467f:17)
    at XMLHttpRequest.handleLoad (xhr.js?b50d:61)

But what I expect from the console.log(err) is

(This is response from postman)
{
    "message": "Error creating new user.",
    "error": {
        "code": "auth/invalid-password",
        "message": "The password must be a string with at least 6 characters."
    }
}

I have no idea what is happening.

1

1 Answers

5
votes

Try this

 console.log(err.response)

To make the code cleaner you can destructure the argument:

  .catch(({ response }) => {
    console.log('fail');
    console.log(response)
  })

If you want to use some other property name instead of response you can do it like this:

  .catch(({ response: err }) => {
    console.log('fail');
    console.log(err)
  })

The problem is when the console.log tries to output the error, the string representation is printed, not the object structure, so you do not see the .response property.

Here you can read about https://github.com/axios/axios/issues/960