#Custom error message in Nuxt 3 API

8 messages · Page 1 of 1 (latest)

outer shoal
#

Hi, I am writing an app that let people register their email
When if the email already exist in the database, the server should throw an error

I am using useFetch:

const { data, error } = await useFetch('api/route')

if (error.value) {
  console.error(error)
}

But the above only gives ambiguous error to the users
i.e.

- Error:  (500 Internal Server Error (api/route))

I would like the error to be more verbose for the users
i.e.

+ Error: email is already in used

Is there a nuxt built-in way to do this?
if so, please you point me to the docs

If there's no built in way doing it, how would you do it?
Can you point me to some useful resource?
A high level view of the design is high appreciated

granite igloo
#

Hi, what you could do is, in your api endpoint, throw a 500 error and return the message as a json object, so you can access and display it in your client.

#

Because I am not sure if you do a throw new Error('my message') that the client gets these messages.

bright sail
granite igloo
bright sail
#

I'm aware that I have also had problems sending the correct error description to the client. I'm unsure if this is the best way, but I've solved it as followed:

// server/api/auth/login.post.ts
const error = {
  ...err
  message: JSON.stringify(errorObject),
};

throw createError(error);

// pages/login.vue
import { destr } from "destr";
const errors = ref(null);
const submit = async () => {
  const response = await $fetch('/api/v1/auth/login', {
    method: 'POST',
    body: {
      key: 'phone_password',
      creditials,
    },
  }).catch((error) => {
    errors.value = destr(error.data.message);
  });

  if( response ) {
    // we have the user!
  }
}

As the doc mentioned, when wanting to make a network request based on user interaction, $fetch is almost always the correct handler.
Link https://nuxt.com/docs/getting-started/data-fetching

Nuxt

Nuxt provides composables to handle data fetching within your application.

outer shoal
#

Late reply, but thank you both
you guys rock

i will try the solution myself first and mark this as answered

outer shoal
#

I forgot to update here
throw createError() is exactly what I was looking for

// /server/api/user/index.post.ts

if (userExist) {
  throw createError({
    statusCode: 500,
    statusMessage: `${user.fullName} already exist`
  })
}

Thanks for the help