Setting Up a Basic Error Handling Route in SvelteKit (+error.svelte)
Nobody likes errors, but they happen. Network glitches, server hiccups, typos in URLs – they're an inevitable part of the web. As developers, while we strive to prevent them, our next most important job is to handle them gracefully. A generic browser error page or a cryptic message is confusing and frustrating for users.
Thankfully, SvelteKit provides a straightforward and elegant way to manage errors using a special route file: +error.svelte.
What is +error.svelte?
+error.svelte is a Svelte component that SvelteKit automatically renders whenever an error occurs during navigation or data loading within a specific part of your application. Think of it as a safety net that catches unexpected issues and presents a user-friendly page instead of a crash or a default browser error.
Why Bother with Custom Error Pages?
- User Experience (UX): A custom error page, even a simple one, feels much more professional and less jarring than a default browser error (like "404 Not Found" or a blank screen with a console error).
- Branding: It keeps the user within your site's look and feel, reinforcing your brand even when things go wrong.
- Guidance: You can provide helpful information, like suggesting the user check the URL, go back to the homepage, or contact support.
- Debugging (Development): During development, it can display useful error details that help you track down the problem faster.
Setting Up Your First +error.svelte
It's surprisingly simple!
Location: Create the file
+error.svelteinside yoursrc/routesdirectory.src/ └── routes/ ├── +page.svelte ├── +layout.svelte └── +error.svelte <-- Create this file └── about/ └── +page.sveltePlacing it at the root level (
src/routes) makes it the default error handler for your entire application unless overridden by a more specific+error.sveltedeeper in the routing tree (more on that later).Basic Content: Add the following code to your new
src/routes/+error.svelte:<script> // Import the 'page' store to access error details import { page } from '$app/stores'; </script> <div class="error-container"> <h1>Oops! Something went wrong.</h1> {#if $page.status} <h2>Error Code: {$page.status}</h2> {/if} {#if $page.error?.message} <p class="error-message">Details: {$page.error.message}</p> {/if} <p>Sorry about that! Please try again later or return home.</p> <a href="/">Go to Homepage</a> </div> <style> .error-container { font-family: sans-serif; text-align: center; padding: 4rem 1rem; max-width: 600px; margin: 5rem auto; border: 1px solid #ddd; border-radius: 8px; background-color: #f9f9f9; } h1 { color: #d9534f; /* Bootstrap's danger color */ margin-bottom: 1rem; } h2 { color: #555; margin-bottom: 1.5rem; } .error-message { background-color: #eee; padding: 0.5rem; border-radius: 4px; color: #333; margin-bottom: 1.5rem; word-break: break-word; /* Prevent long messages from breaking layout */ } a { display: inline-block; margin-top: 1rem; padding: 0.75rem 1.5rem; background-color: #0275d8; /* Bootstrap's primary color */ color: white; text-decoration: none; border-radius: 4px; transition: background-color 0.2s ease; } a:hover { background-color: #025aa5; } </style>
Understanding the Code
import { page } from '$app/stores';: This imports SvelteKit's reactivepagestore. When an error occurs, SvelteKit populates this store with error details.$page.status: This reactive property holds the HTTP status code of the error (e.g.,404for "Not Found",500for "Internal Server Error").$page.error: This reactive property holds an error object. It typically has at least amessageproperty containing a description of the error. We use optional chaining (?.message) because theerrorobject itself might sometimes be null or undefined, although it usually exists when+error.svelteis rendered.
How Does SvelteKit Use It?
When an error occurs that SvelteKit catches:
- During Server-Side Rendering (SSR) or in
loadfunctions: If you throw an error using SvelteKit'serrorhelper (e.g.,throw error(404, 'Not Found')) in a+page.server.jsor+layout.server.jsfile. - Client-Side Navigation: If the user tries to navigate to a route that doesn't exist.
- Other Uncaught Exceptions: Sometimes, other uncaught exceptions during rendering or loading might trigger it.
SvelteKit stops processing the intended route and looks for the nearest +error.svelte file by searching upwards from the directory where the error occurred. If it doesn't find one in the current directory or parent directories, it eventually uses the root src/routes/+error.svelte.
Triggering Errors for Testing
- 404 Not Found: Simply navigate to a URL in your application that doesn't correspond to any defined route (e.g.,
/this-page-does-not-exist). You should see your custom error page displaying "Error Code: 404". Server Error (e.g., 500): Create a temporary test route. Add a
+page.server.jsfile like this:// src/routes/test-error/+page.server.js import { error } from '@sveltejs/kit'; export function load() { // Simulate a server-side problem throw error(500, 'Something went terribly wrong on the server!'); }Now, navigate to
/test-errorin your browser. You should see your custom error page displaying "Error Code: 500" and the specific message. Remember to remove this test route afterward!
Important Considerations
- Layouts: The root
+error.svelte(src/routes/+error.svelte) does not inherit from your root+layout.svelte. It's a completely standalone page. This is intentional, as your layout itself might be causing the error! However, nested error pages (e.g.,src/routes/admin/+error.svelte) do inherit layouts from their parent directories. - Customization: You can make your error page much more sophisticated. Conditionally display different messages or suggestions based on the
$page.statuscode (e.g., specific advice for 404 vs. 500). - Security: Be cautious about displaying raw error messages (
$page.error.message) directly from server errors in a production environment. They might leak sensitive information. Consider logging the detailed error on the server and showing a generic, user-friendly message on the page. - Nested Error Pages: You can create
+error.sveltefiles within subdirectories (e.g.,src/routes/admin/+error.svelte) to handle errors specific to that section of your site differently.
Conclusion
Setting up a basic +error.svelte page in SvelteKit is a quick win for improving the robustness and user experience of your application. It replaces jarring default errors with a branded, helpful page, making unexpected issues less frustrating for your users. Start with the simple example above, and customize it to fit the needs and style of your project!
Logging errors to a server (e.g., using Sentry or Firebase).