Learn Nuxt · 11/12

Error Handling: Building Resilient Applications

7 min read

Error Handling: Building Resilient Applications

Hey there! Let's talk about something that isn't the most glamorous part of web development, but is absolutely critical for a good user experience: error handling. 🐛

Think of your Nuxt application as a high-tech package delivery service. Most of the time, packages (user requests) get to their destination (the correct page) without a hitch. But what happens when a package is addressed to a non-existent location, or the contents get damaged in transit? That's where a good error handling system comes in. It's your customer service department, ensuring that when things go wrong, your users aren't left staring at a confusing blank screen.

In this guide, we'll cover the essential tools Nuxt provides to catch these fumbles and handle them gracefully, making your app more robust and user-friendly.


1. Creating a Custom error.vue Page 🚨

The Problem: When a serious, application-breaking error occurs, Nuxt has to stop everything and show an error page. By default, this page is... well, a bit bland. It doesn't match your brand and isn't very helpful to the user.

The Solution: Nuxt allows you to create your own global error page by adding a single file: error.vue in the root of your project (right next to app.vue). This file acts as a universal template for displaying any fatal errors that occur, whether on the server or the client.

Imagine this is your central customer service desk. Any time a major problem is flagged in your delivery system, the customer is sent here for a clear explanation and help.

How to Build It:

  1. Create a file named error.vue in the root of your project.
  2. This component will receive a special error prop containing details like the statusCode (e.g., 404, 500) and a message.

Here is a basic but solid error.vue page:

vue
<!-- ~/error.vue -->
<template>
  <div class="flex flex-col items-center justify-center min-h-screen bg-gray-100">
    <h1 class="text-8xl font-bold text-blue-600">{{ error.statusCode }}</h1>
    <p class="text-2xl mt-4 mb-8">{{ errorMessage }}</p>
    <button
      @click="handleError"
      class="px-6 py-3 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition"
    >
      Go Back Home
    </button>
  </div>
</template>

<script setup>
const props = defineProps({
  error: Object,
});

// A computed property to provide a user-friendly message based on the status code
const errorMessage = computed(() => {
  if (props.error.statusCode === 404) {
    return "Oops! The page you're looking for could not be found.";
  }
  return "An unexpected error occurred. Please try again later.";
});

// A function to clear the error and redirect the user
const handleError = () => clearError({ redirect: "/" });
</script>

What's Happening Under the Hood?
When a fatal error is triggered, Nuxt halts the normal rendering process and instead renders your error.vue component, passing the error details to it as a prop. It's a special component, not part of your regular page routing.


2. Handling API and Data Fetching Errors 📦

The Problem: Modern apps live on data. You're constantly fetching information from APIs. But what if an API server is down, or a network request fails? Your page could crash or show incomplete information.

The Solution: The useFetch composable, Nuxt's workhorse for data fetching, has built-in error handling. It returns an error ref along with the data ref. You can check if this error ref has a value to gracefully handle any issues.

Think of useFetch as your delivery driver. If they go to pick up a package (data) and the warehouse (API) is closed, they don't just give up. They come back with a report (the error object) so you can decide what to do next.

Industry Practice:
It's common to check for an error immediately after the await useFetch call. If an error exists, you can either show a message on the page or trigger a full-screen error page.

vue
<!-- pages/products/[id].vue -->
<template>
  <div>
    <!-- This v-if will show an error message right on the page -->
    <div v-if="error" class="p-4 bg-red-100 text-red-700 rounded">
      <p>Could not load product data. Please try again later.</p>
      <p>Error: {{ error.message }}</p>
    </div>
    <!-- Otherwise, show the product data -->
    <div v-else-if="product">
      <h1>{{ product.title }}</h1>
      <p>{{ product.description }}</p>
    </div>
  </div>
</template>

<script setup>
const route = useRoute();
const { data: product, error } = await useFetch(
  `https://fakestoreapi.com/products/${route.params.id}`
);

// You can also choose to throw a fatal error to show your custom error.vue page
if (error.value) {
  // This will stop rendering this page and show the error.vue page instead
  throw createError({
    statusCode: error.value.statusCode,
    statusMessage: `Could not fetch product with ID: ${route.params.id}`,
    fatal: true, // `fatal: true` is crucial for triggering the full-screen error page on the client-side.
  });
}
</script>

3. Throwing and Clearing Errors with showError and clearError 📢

The Problem: Errors don't just happen during data fetching. They can occur anywhere—after a user clicks a button, in a complex calculation, or in a component's lifecycle hook. How do you manually trigger your beautiful error.vue page from anywhere in your app?

The Solution: Nuxt provides two powerful utility functions: showError and clearError.

  • showError: This is like pulling the emergency alarm. You can call it anywhere in your client-side code (or on the server within plugins and middleware) to immediately trigger the full-screen error.vue page.
  • clearError: This is the reset button. It clears the active error, allowing the user to navigate away from the error page. It's essential for providing an exit path for your users.

Practical Example:
Imagine a user trying to submit a form, but a client-side validation check reveals an unrecoverable issue.

vue
<!-- components/CheckoutForm.vue -->
<template>
  <form @submit.prevent="processPayment">
    <!-- form inputs -->
    <button type="submit">Pay Now</button>
  </form>
</template>

<script setup>
const canConnectToPaymentGateway = ref(false); // Let's pretend this is a real check

function processPayment() {
  if (!canConnectToPaymentGateway.value) {
    // Manually trigger the global error page
    showError({
      statusCode: 503, // Service Unavailable
      message: "We are unable to connect to our payment provider right now.",
    });
  }
  // ... proceed with payment
}
</script>

Your error.vue page would then display this message, and the "Go Back Home" button we created earlier uses clearError({ redirect: '/' }) to get the user back to safety.


4. Handling 404s and Route Fallbacks 🗺️

The Problem: A user mistypes a URL or follows a broken link. They've landed on a route that doesn't exist. You need to tell them they're lost and guide them back. This is the classic "404 Not Found" error.

The Solution: Nuxt handles this beautifully out of the box.

  1. The error.vue Page: Your custom error page will automatically be shown for any 404 errors. The error prop will have a statusCode of 404, which you can use to display a specific "Page Not Found" message, just like in our example.

  2. Catch-all Routes (Advanced): For more complex scenarios, like handling old URLs or custom routing logic, you can create a catch-all route. This is a page file named [...slug].vue inside your pages directory. This component will intercept any route that doesn't match a more specific page.

Think of the catch-all route as a friendly guide who stands at the end of all known paths. If someone wanders off, this guide can check their map (the URL) and try to redirect them or offer help, instead of just sending them to customer service (error.vue).

Example of a Catch-all Route:

vue
<!-- pages/[...slug].vue -->
<template>
  <div>
    <h1>Page Not Found</h1>
    <p>We couldn't find a page at <code>{{ $route.path }}</code>.</p>
    <p>Maybe you were looking for one of our products?</p>
    <!-- Add links or a search bar here -->
  </div>
</template>

<script setup>
// You might want to set the response code to 404 for SEO purposes
import { setResponseStatus } from "nuxt/app";
setResponseStatus(404);
</script>

Industry Standard: For most applications, customizing the error.vue page for 404s is sufficient and the recommended approach. Use a catch-all route only when you need custom logic to handle unknown paths, such as redirecting legacy URLs.


Further Reading & References

Challenge

You are tasked with building a robust custom error page for a Nuxt.js application. Create a single file component that will act as the error.vue page to handle application-wide errors.

Requirements:

  1. The component must define and accept a prop named error, which will be an object containing error details like statusCode and message.
  2. Dynamically display a title and a message based on the error.statusCode:
    • For a 404 status code, the title must be <h1>Page Not Found</h1> and the message must be <p>Sorry, the page you are looking for could not be found.</p>.
    • For a 500 status code, the title must be <h1>Internal Server Error</h1> and the message must be <p>An unexpected error occurred. We are working to fix it.</p>.
    • For all other error status codes, display a generic title <h1>An Error Occurred</h1> and render the error.message inside a <p> tag.
  3. Include a <button> with the text "Go Back Home".
  4. When this button is clicked, it must call a function that uses the appropriate Nuxt utility to clear the current error and redirect the user to the root path (/).

Expected result

Your solution should be a complete Vue single-file component.

The <script setup> block must:

  • Use defineProps to accept an error prop of type Object.
  • Define a handler function, e.g., handleErrorClear, that calls the clearError Nuxt utility.
  • The clearError function must be invoked with an object that has a redirect property set to '/'.

The <template> block must:

  • Use v-if, v-else-if, and v-else directives to conditionally render the correct <h1> and <p> elements according to the error.statusCode.
  • Include a <button> element with a @click directive that calls your handler function.
vue

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.