+error.svelte in SvelteKit: What It Is and How It Works
+error.svelte is a special SvelteKit component that automatically displays when an error happens during page loading or navigation. It lets you show friendly error messages or custom UI instead of a blank or broken page.How It Works
Imagine your app is like a restaurant. When something goes wrong in the kitchen, you want to tell your guests politely instead of leaving them confused. +error.svelte is like the waiter who delivers a clear message when the kitchen has a problem.
In SvelteKit, if a page or data loading fails, the framework looks for a +error.svelte file in the route folder. If it exists, SvelteKit shows this component instead of the broken page. This component receives an error object with details about what went wrong, so you can display a helpful message.
This system helps keep your app user-friendly by catching errors early and showing a nice fallback UI automatically.
Example
This example shows a simple +error.svelte that displays the error message and status code.
<script> export let error; export let status; </script> <h1>Error {status}</h1> <p>{error.message}</p>
When to Use
Use +error.svelte whenever you want to handle errors gracefully in your SvelteKit app. It is especially useful for:
- Showing user-friendly messages when a page is missing (404 errors).
- Handling server or network errors during data loading.
- Customizing the look and feel of error pages to match your app’s style.
Without it, users might see a blank screen or a generic browser error, which can be confusing or frustrating.
Key Points
+error.svelteis a special file that SvelteKit uses to show errors.- It receives
errorandstatusprops to display error details. - Helps improve user experience by showing friendly error messages.
- Automatically used when a route or data loading fails.
- You can customize it per route or globally.
Key Takeaways
+error.svelte shows custom error pages automatically in SvelteKit.