Skip to content

Error handling

Effective error handling is a fundamental pillar of software development and system management, playing a vital role in ensuring the stability, performance, and overall user experience of your software, applications, and systems.

CreateError function

The createError function helps you create error objects with all the necessary details, which you can then throw to manage errors in your app. Depending on where the error is thrown and how you set certain properties, you can control whether the error triggers a full-screen error page or is handled more gently within your code: function createError (err: { cause, data, message, name, stack, statusCode, statusMessage, fatal }): Error

Note that in frontend it will throw a non-fatal error, so you can set the fatal argument to true to trigger the error page.

Here is a full example:

sh
const { data, error } = await useFetch<any>(`/api/${param}`)

if (error.value) {
    Sentry.captureException(error.value)
    throw createError({ statusCode: error.value.statusCode, statusMessage: error.value.message, fatal: true })
}

Error page

In the root directory, you should add an error.vue file, which will always be displayed when an error occurs. For example:

sh
<template>
  <div>
    <h1>An error occurred</h1>
    <NuxtLink to="/">Home page</NuxtLink>
  </div>
</template>

Here the error is handle not only by explicitly informing on the situation but also by providing an immediate solution with a redirection.

Released under the MIT License.