0
0
Svelteframework~15 mins

Error pages (+error.svelte) - Deep Dive

Choose your learning style9 modes available
Overview - Error pages (+error.svelte)
What is it?
Error pages in SvelteKit are special components that show up when something goes wrong during navigation or data loading. The +error.svelte file is a dedicated component that handles these errors gracefully by displaying helpful messages to users. It replaces default browser error messages with custom, user-friendly content. This helps keep your app looking polished even when unexpected problems occur.
Why it matters
Without error pages, users see confusing or ugly browser error messages that break the experience. Custom error pages let you explain what happened, guide users on what to do next, and keep your app professional. They prevent frustration and help maintain trust, especially when network issues or bugs happen. This improves overall user satisfaction and reduces support requests.
Where it fits
Before learning error pages, you should understand basic SvelteKit routing and how components work. After mastering error pages, you can explore advanced error handling like server-side error responses, fallback UI, and integrating error logging services. Error pages fit into the broader topic of building resilient, user-friendly web apps.
Mental Model
Core Idea
An error page is a special Svelte component that catches and displays errors during navigation or data loading to keep the app user-friendly.
Think of it like...
It's like a friendly receptionist who steps in when something goes wrong in a building, explains the problem clearly, and guides visitors on what to do next instead of leaving them confused.
┌───────────────┐
│ User requests │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Route loads   │
│ data & page   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Error occurs? │──No──▶ Render page normally
│               │
└──────┬────────┘
       │Yes
       ▼
┌───────────────┐
│ +error.svelte │
│ renders error │
└───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is +error.svelte file
🤔
Concept: Introducing the special +error.svelte file in SvelteKit that handles errors.
In SvelteKit, if an error happens during page loading or navigation, the framework looks for a +error.svelte file in the current route or parent routes. This file is a Svelte component that receives error details and displays a custom error message. If no +error.svelte exists, a default ugly error message shows.
Result
When an error occurs, the +error.svelte component renders instead of the broken page.
Understanding that +error.svelte is a reserved filename that automatically catches errors helps you control user experience during failures.
2
FoundationBasic structure of +error.svelte
🤔
Concept: How to create a simple +error.svelte component that shows error info.
A +error.svelte file exports special 'error' and 'status' props. You can use these to show the error message and HTTP status code. For example:

{status}

{error.message}

This shows the error status and message to the user.
Result
Users see a clear error code and message instead of a blank or broken page.
Knowing the props passed to +error.svelte lets you customize error display based on error details.
3
IntermediateError propagation and hierarchy
🤔Before reading on: Do you think +error.svelte files in parent routes catch errors from child routes? Commit to your answer.
Concept: How errors bubble up through nested routes and how +error.svelte files in parent folders can catch child errors.
If a child route throws an error but doesn't have its own +error.svelte, SvelteKit looks up the folder tree for a +error.svelte to handle it. This means you can have a global error page at the root or more specific ones in subfolders. This hierarchy lets you customize error handling per section or globally.
Result
Errors in nested routes can be caught by nearest +error.svelte up the folder tree.
Understanding error bubbling helps you organize error pages efficiently and avoid duplication.
4
IntermediateCustomizing error content and style
🤔Before reading on: Can you customize the look of error pages fully with +error.svelte? Commit to your answer.
Concept: Using Svelte features to style and add interactivity to error pages.
Since +error.svelte is a normal Svelte component, you can add CSS, images, buttons, or links to help users recover. For example, add a button to go back home or retry. You can also style the page with CSS or Tailwind to match your app's look. This makes error pages feel part of your app, not an afterthought.
Result
Error pages become visually consistent and user-friendly with helpful navigation.
Knowing +error.svelte is fully customizable encourages better user experience design during errors.
5
IntermediateHandling errors from load functions
🤔Before reading on: Do you think errors thrown in load functions automatically show +error.svelte? Commit to your answer.
Concept: How errors thrown in page or layout load functions trigger +error.svelte rendering.
If a load function throws an error or returns a non-2xx status, SvelteKit stops normal rendering and shows the nearest +error.svelte. This lets you handle data loading failures gracefully. You can throw errors with custom messages and status codes to control what users see.
Result
Load errors cause +error.svelte to render with error details.
Understanding this connection helps you design robust data loading with clear error feedback.
6
AdvancedUsing error boundaries for partial recovery
🤔Before reading on: Can +error.svelte be used to recover only part of a page? Commit to your answer.
Concept: How +error.svelte acts as an error boundary to isolate errors in parts of the app.
By placing +error.svelte files in nested layouts or routes, you can catch errors locally and show fallback UI only for that section. This prevents the whole app from crashing. For example, a sidebar load error can show a sidebar error message but keep the main content visible.
Result
Errors are contained and partial UI remains usable.
Knowing error boundaries lets you build resilient apps that degrade gracefully.
7
ExpertAdvanced error handling with hooks and server
🤔Before reading on: Do you think +error.svelte handles server errors automatically without extra code? Commit to your answer.
Concept: How to integrate +error.svelte with server hooks and custom error responses for full control.
You can throw errors in server endpoints or hooks with status and message. SvelteKit passes these to +error.svelte for display. You can also customize error handling in hooks to log errors or modify responses. This lets you build centralized error tracking and user-friendly messages for all error sources.
Result
All errors from client and server routes funnel through +error.svelte with custom logic.
Understanding this integration is key to professional-grade error handling and monitoring.
Under the Hood
When an error occurs during navigation or data loading, SvelteKit intercepts it and looks for a +error.svelte component starting from the current route folder upwards. It then renders this component instead of the normal page. The framework passes the error object and HTTP status as props to +error.svelte. This interception happens in the routing and rendering pipeline, ensuring users never see raw exceptions or broken pages.
Why designed this way?
This design centralizes error handling in a declarative way using special files, fitting SvelteKit's file-based routing philosophy. It avoids scattering error UI code throughout the app and leverages Svelte's component model for flexibility. Alternatives like global error handlers or try-catch everywhere would be more complex and less maintainable.
┌───────────────┐
│ Navigation or │
│ Load triggers │
│ error thrown  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ SvelteKit     │
│ intercepts   │
│ error event   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Search for    │
│ +error.svelte │
│ in route tree │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Render        │
│ +error.svelte │
│ with props    │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does +error.svelte catch errors thrown anywhere in the app? Commit yes or no.
Common Belief:Some think +error.svelte catches all errors globally no matter where they happen.
Tap to reveal reality
Reality:+error.svelte only catches errors during navigation or load functions in routes where it exists or in parent routes. Errors outside routing (like event handlers) are not caught automatically.
Why it matters:Assuming global coverage leads to missing error handling in other parts, causing uncaught exceptions and crashes.
Quick: Can you use +error.svelte to handle HTTP 404 pages? Commit yes or no.
Common Belief:Many believe +error.svelte is only for server errors (500s) and not for 404 Not Found errors.
Tap to reveal reality
Reality:+error.svelte handles all HTTP errors including 404. You can customize messages for different status codes inside it.
Why it matters:Misunderstanding this limits your ability to provide friendly 'page not found' messages, hurting user experience.
Quick: Does throwing an error in a load function always show +error.svelte? Commit yes or no.
Common Belief:Some think throwing any error in load always triggers +error.svelte immediately.
Tap to reveal reality
Reality:Only errors thrown or returned with status in load functions trigger +error.svelte. Returning a normal response with error info does not.
Why it matters:Confusing this causes unexpected UI behavior and debugging frustration.
Quick: Is it safe to expose full error messages to users in +error.svelte? Commit yes or no.
Common Belief:Developers often show raw error messages directly to users for debugging.
Tap to reveal reality
Reality:Exposing raw errors can leak sensitive info. It's better to show friendly messages and log details internally.
Why it matters:Ignoring this risks security leaks and poor user trust.
Expert Zone
1
Errors thrown in server hooks can be caught by +error.svelte only if they propagate through the routing lifecycle; otherwise, they need separate handling.
2
Stacking multiple +error.svelte files in nested routes allows fine-grained error UI control but requires careful design to avoid confusing users with inconsistent messages.
3
Using SvelteKit's load function error handling with typed error objects improves maintainability and enables better tooling support.
When NOT to use
Avoid relying solely on +error.svelte for error handling in interactive event handlers or API calls outside routing. Use try-catch blocks, error boundaries in components, or global error handlers instead.
Production Patterns
In production, teams combine +error.svelte with centralized error logging services and user-friendly fallback UI. They often create a root +error.svelte for global errors and specialized ones in critical app sections. They also sanitize error messages to avoid exposing sensitive info.
Connections
React Error Boundaries
Similar pattern of catching errors in UI components to prevent full app crashes.
Understanding error boundaries in React helps grasp how +error.svelte isolates errors and provides fallback UI in SvelteKit.
HTTP Status Codes
Uses status codes to communicate error types and customize messages.
Knowing HTTP status codes helps you design meaningful error pages that explain problems clearly to users.
Customer Support Ticketing
Both involve capturing error details and presenting them in a user-friendly way to guide next steps.
Seeing error pages as a form of customer support interface highlights the importance of clear communication and recovery options.
Common Pitfalls
#1Showing raw error messages directly to users.
Wrong approach:

{status}

{error.stack}

Correct approach:

{status}

Sorry, something went wrong. Please try again later.

Root cause:Misunderstanding security risks and user experience by exposing internal error details.
#2Not creating +error.svelte, relying on default ugly error page.
Wrong approach:No +error.svelte file in the project.
Correct approach:

{status}

{error.message}

Root cause:Underestimating the importance of user-friendly error handling.
#3Throwing errors in event handlers expecting +error.svelte to catch them.
Wrong approach:function handleClick() { throw new Error('Oops'); }
Correct approach:function handleClick() { try { // code } catch (e) { // show local error UI or notification } }
Root cause:Confusing routing load errors with client-side event errors.
Key Takeaways
+error.svelte is a special SvelteKit file that catches and displays errors during routing and data loading.
It receives error details as props, letting you customize the error message and appearance fully.
Errors bubble up through nested routes, so parent +error.svelte files can catch child errors for flexible handling.
Custom error pages improve user experience by replacing ugly default messages with friendly guidance.
Advanced use includes error boundaries, server integration, and security-conscious error display.