RazorMx
RazorMx

Reputation: 427

How can I get the error response body in Nuxt 3 using useFetch?

I have a /services/userService.js file in Nuxt 3:

const baseURL = 'http://localhost:8080/api/auth/'
const headers = {
  Accept: 'application/json',
  'Content-type': 'application/json',
}

export default {
  signinNewUser(firstName, secondName, email, password) {
    return useFetch('/signup', {
      method: 'POST',
      baseURL: baseURL,
      headers: headers,
      body: {
        firstName,
        secondName,
        email,
        password,
      },
    })
  },
}

And I have the following function in /store/user.js

async registerUser(firstName, secondName, email, password) {
      return userService
        .signinNewUser(firstName, secondName, email, password)
        .then(
          (res) => {
            const data = res.data.value
            const error = res.error.value
            if (error) {
              console.log(error)
            } else {
              this.registered = true
            }
          },
          (error) => {
            console.log('exception...')
            console.log(error)
          }
        )
    },

My auth API can answer with a 400 status code and different error messages in the response body like:

{"message":"Error: Email is already in use!"}
{"message":"Error: FirstName is already in use!"}

etc...

I want to be able to access those messages in order to show to the user different error messages so he/she knows how to fix the issue.

How can I achieve that?

I tried accessing the error object but it doesn't contain a reference to the response body, data object is null

Upvotes: 3

Views: 11024

Answers (1)

GeorgesA
GeorgesA

Reputation: 403

You can access the body of the error response using the data key from the error reference object. An http error will not always raise an error in the composable.

const data = error.value.data;
async registerUser(firstName, secondName, email, password) {
      return userService
        .signinNewUser(firstName, secondName, email, password)
        .then(
          (res) => {
            const data = res.data.value
            const error = res.error.value
            if (error) {
              console.log(error)
              this.error = error.data; // <== To handle the error data.
            } else {
              this.registered = true
            }
          },
          (error) => {
            console.log('exception...')
            console.log(error)
          }
        )
    },

Also, the useFetch composable allows you to use interceptors to access the data in an other fashion, please refer to the documentation on the subject.

Upvotes: 4

Related Questions