SvelteKit 12 🧡 Error Handling & Redirects — Throwing error(), redirect(), handling expected vs. unexpected errors, and custom error pages
In SvelteKit, navigation control and failure management are handled through the simple, powerful act of throwing specific objects. Instead of returning complex “failure” state objects from your load functions or API actions, you simply throw an error() or redirect() result. This halts execution immediately, signaling the framework to take over the control flow, ensuring your application remains in a predictable, consistent state.
Handling errors effectively involves a two-pronged approach: “expected” errors—which you catch and throw intentionally when a user reaches a state they shouldn’t—and “unexpected” errors—which are unhandled exceptions that the framework catches to provide a safe, generic fallback. By mastering these patterns, you can create a seamless user experience that guides visitors through the application while providing graceful exits when things go wrong.
This chapter covers the mechanics of triggering redirects, differentiating between failure types, and customizing the global error pages that users see when the unexpected happens.
Key point: Throwing SvelteKit’s error() and redirect() halts execution immediately and delegates control to the framework, which automatically manages the transition to the correct page or error state without requiring additional boilerplate in your logic.
Why error handling exists
The navigation control problem. Users often attempt to access resources they aren’t authorized to see. Redirecting them programmatically is necessary to maintain route-level security.
The partial failure problem. Data fetching is unreliable. When an API call fails, the application needs a standardized way to signal that a specific component or page cannot render.
The unexpected exception problem. Every application has bugs. Without a centralized way to catch unhandled exceptions, the server might return raw tracebacks, which are a security risk and a poor user experience.
The state consistency requirement. If a load function partially completes and then finds a problem, you don’t want to partially render the page. Halting execution prevents the UI from entering a “half-rendered” or invalid state.
The user feedback loop. When something goes wrong, the user deserves clear communication. Centralized error pages allow you to provide helpful links or “back” buttons instead of a blank screen or a generic browser error.
a. error() and expected vs. unexpected errors
throw error(status, message) is the primary tool for expected failures. When you know a resource is missing (like a post ID that doesn’t exist), you throw a 404. This is an “expected” error because you’ve planned for this outcome.
// +page.server.ts
import { error } from '@sveltejs/kit';
export const load = ({ params }) => {
const data = fetchPost(params.id);
if (!data) {
throw error(404, 'Post not found'); // Expected failure
}
return data;
};
“Unexpected” errors are different—these are standard JavaScript throw new Error() calls or unhandled promise rejections. SvelteKit catches these automatically, treats them as 500 (Internal Server Error) status, and hides the implementation details from the user to prevent security leaks.
b. redirect() and navigation flow
Redirects are simply jumps in the navigation history. throw redirect(status, location) is typically used in hooks.server.ts for auth guards or in load functions when a user needs to be sent to a login screen.
// +page.server.ts
import { redirect } from '@sveltejs/kit';
export const load = ({ locals }) => {
if (!locals.user) {
throw redirect(303, '/login'); // Redirect to login
}
};
Status codes 302 (Found) and 303 (See Other) are the most common. 303 is generally preferred for redirects after a form action or auth check, as it instructs the browser to perform a GET request to the target URL.
c. The +error.svelte page and hierarchy
SvelteKit uses a filesystem-based hierarchy for error pages. A +error.svelte at the root of src/routes/ acts as the global catch-all. If you create a +error.svelte inside a specific sub-folder (e.g., src/routes/blog/+error.svelte), it will handle errors thrown only within that route hierarchy.
<!-- src/routes/+error.svelte -->
<script>
import { page } from '$app/stores';
</script>
<h1>{$page.status}: {$page.error?.message}</h1>
<button onclick={() => history.back()}>Go back</button>
This page has access to the $page store, where status and error properties tell you exactly what went wrong, allowing you to tailor the UI to the specific failure.
Complete Example Session
// ============================================
// PART 1: THROWING AN EXPECTED ERROR
// ============================================
throw error(404, { message: 'Not found' });
// ============================================
// PART 2: TRIGGERING A REDIRECT
// ============================================
throw redirect(303, '/dashboard');
// ============================================
// PART 3: CATCHING UNEXPECTED ERRORS
// ============================================
try {
await databaseOperation();
} catch (e) {
// SvelteKit treats unhandled errors as 500s
throw e;
}
// ============================================
// PART 4: ACCESSING ERROR DATA IN UI
// ============================================
// +error.svelte
$page.status; // 404
$page.error.message; // 'Not found'
This sequence covers the intentional path of failure control, from throwing to rendering.
Quick Reference
Throwing Functions
| Function | Usage | Best For |
|---|---|---|
error(code, msg) | throw error(404, '...') | Expected failures |
redirect(code, loc) | throw redirect(303, '...') | Auth or nav flow |
Error Hierarchy
| File | Scope |
|---|---|
src/routes/+error.svelte | Global fallback |
src/routes/path/+error.svelte | Route-specific errors |
Best Practices
✅ Do This:
// Throw specific status codes
throw error(403, 'Forbidden'); // ✅
// Use 303 for redirects
throw redirect(303, '/login'); // ✅
// Provide helpful messages
throw error(404, 'Post ID not found'); // ✅
❌ Don’t Do This:
// Return error object instead of throwing
return { error: 'Not found' }; // ❌
// Catch and suppress errors without re-throwing
try { ... } catch (e) { console.log(e); } // ❌
// Use 302 indiscriminately
throw redirect(302, '/home'); // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Infinite Loop | Redirect in hooks.server.ts | Exclude login route |
| Missing UI | No +error.svelte | Create global error file |
| 500 Errors | Unhandled promises | Use try/catch + error() |
| Misleading Status | Generic status codes | Use semantic HTTP codes |
Real-World Examples
1. Auth Guard
if (!user) throw redirect(303, '/login');
2. Resource Missing
if (!post) throw error(404, 'Post missing');
3. Database Failure
try { await db.query(); } catch { throw error(500, 'DB error'); }
4. Permission Denied
if (!isAdmin) throw error(403, 'Admin only');
5. Redirect After Action
throw redirect(303, '/success');
6. Custom Error Message
throw error(400, 'Invalid input');
7. Global Catch-All
// +error.svelte
8. Route-Specific Error
// /blog/+error.svelte
9. Status 418
throw error(418, 'I am a teapot');
10. Redirect to External
throw redirect(303, 'https://external.com');
Visual
Execution Halt
┌──────────────────────────────────────────────┐
│ load() ──► check ──► throw error() │
│ │ │
│ The rest of the function is skipped. │
│ SvelteKit takes control immediately. │
└──────────────────────────────────────────────┘
Hierarchy of +error.svelte
┌──────────────────────────────────────────────┐
│ src/routes/+error.svelte (Global) │
│ │ │
│ └── src/routes/admin/+error.svelte │
│ │
│ Errors bubble up to the closest parent. │
└──────────────────────────────────────────────┘
Expected vs Unexpected
┌──────────────────────────────────────────────┐
│ Expected (throw error) ──► Handled UI │
│ │
│ Unexpected (exception) ──► Generic 500 UI │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Success | Return data |
| Expected Fail | throw error() |
| Navigation | throw redirect() |
| UI Component | +error.svelte |
| Store | $page |
Key takeaways:
- Throw, don’t return. Throwing ensures execution stops immediately, preventing your code from trying to render with invalid or missing data.
- Differentiate failures. Use
error()for anticipated problems (404s, 403s) and let unhandled exceptions fall through as 500s. - Redirects are flow control. Use
redirect()to keep the user within authorized bounds and to manage navigation after state-changing actions. - Hierarchy matters. Place
+error.sveltefiles at the root for a global fallback and in subdirectories to handle specific route domains differently. - Access error data. Use
$page.errorand$page.statusin your+error.sveltefiles to provide context-aware feedback to the user.
Remember: Error handling is the difference between a fragile application and a robust one. By treating errors as standard parts of your navigation flow and leveraging SvelteKit’s filesystem-based error catching, you turn potential crashes into helpful, navigable user journeys.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!