Nuxt/docs/content/3.api/3.utils/create-error.md
Mitsuki Fukunaga 38158cf261
docs: add explicit createError import (#6050)
Co-authored-by: Pooya Parsa <pooya@pi0.io>
2022-07-22 09:55:54 +02:00

1.3 KiB

createError

You can use this function to create an error object with additional metadata. It is usable in both the Vue and Nitro portions of your app, and is meant to be thrown.

Parameters:

  • err: { cause, data, message, name, stack, statusCode, statusMessage, fatal }

Throwing errors in your Vue app

If you throw an error created with createError:

  • on server-side, it will trigger a full-screen error page which you can clear with clearError.
  • on client-side, it will throw a non-fatal error for you to handle. If you need to trigger a full-screen error page, then you can do this by setting fatal: true.

Example

::StabilityEdge{title="Auto import of createError"} In the current version, add import { createError } from 'h3' in order to use createError. ::

<script setup>
const route = useRoute()
const { data } = await useFetch(`/api/movies/${route.params.slug}`)
if (!data.value) {
  throw createError({ statusCode: 404, statusMessage: 'Page Not Found' })
}
</script>

Throwing errors in API routes

You can use createError to trigger error handling in server API routes.

Example

export default eventHandler(() => {
  throw createError({
    statusCode: 404,
    statusMessage: 'Page Not Found'
  })
}

::ReadMore{link="/guide/features/error-handling"} ::