0
# Error Handling
1
2
SvelteKit provides utilities for creating HTTP errors and redirects that integrate seamlessly with the framework's error handling system.
3
4
## Capabilities
5
6
### Error Function
7
8
Throws an HTTP error that SvelteKit will handle appropriately, returning an error response without invoking the `handleError` hook.
9
10
```typescript { .api }
11
/**
12
* Throws an error with a HTTP status code and an optional message.
13
* When called during request handling, this will cause SvelteKit to
14
* return an error response without invoking `handleError`.
15
* @param status - HTTP status code (must be 400-599)
16
* @param body - Error body that conforms to App.Error type or string
17
* @throws HttpError - Instructs SvelteKit to initiate HTTP error handling
18
* @throws Error - If the provided status is invalid
19
*/
20
function error(status: number, body: App.Error | string): never;
21
```
22
23
**Usage Examples:**
24
25
```typescript
26
import { error } from '@sveltejs/kit';
27
28
// In a load function
29
export async function load({ params }) {
30
const post = await getPost(params.id);
31
32
if (!post) {
33
throw error(404, 'Post not found');
34
}
35
36
if (!post.published) {
37
throw error(403, 'Post not published');
38
}
39
40
return { post };
41
}
42
43
// In an API endpoint
44
export async function GET({ params }) {
45
const user = await getUser(params.id);
46
47
if (!user) {
48
throw error(404, {
49
message: 'User not found',
50
code: 'USER_NOT_FOUND'
51
});
52
}
53
54
return json(user);
55
}
56
```
57
58
### HTTP Error Type Guard
59
60
Checks whether an error was thrown by the `error()` function, with optional status filtering.
61
62
```typescript { .api }
63
/**
64
* Checks whether this is an error thrown by error().
65
* @param e - The object to check
66
* @param status - Optional status code to filter for
67
* @returns Type predicate indicating if e is an HttpError
68
*/
69
function isHttpError(e: unknown, status?: number): boolean;
70
```
71
72
**Usage Examples:**
73
74
```typescript
75
import { isHttpError, error } from '@sveltejs/kit';
76
77
try {
78
await someOperation();
79
} catch (e) {
80
if (isHttpError(e)) {
81
console.log('HTTP error occurred:', e.status, e.body);
82
throw e; // Re-throw to let SvelteKit handle it
83
}
84
85
if (isHttpError(e, 404)) {
86
console.log('Specific 404 error occurred');
87
}
88
89
// Handle other error types
90
throw error(500, 'Internal server error');
91
}
92
```
93
94
### Redirect Function
95
96
Throws a redirect that SvelteKit will handle by returning a redirect response.
97
98
```typescript { .api }
99
/**
100
* Redirect a request. When called during request handling, SvelteKit will return a redirect response.
101
* Make sure you're not catching the thrown redirect, which would prevent SvelteKit from handling it.
102
* @param status - HTTP redirect status code (300-308)
103
* @param location - The location to redirect to
104
* @throws Redirect - Instructs SvelteKit to redirect to the specified location
105
* @throws Error - If the provided status is invalid
106
*/
107
function redirect(status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308, location: string | URL): never;
108
```
109
110
**Common Status Codes:**
111
- `303 See Other`: Redirect as a GET request (often used after a form POST)
112
- `307 Temporary Redirect`: Redirect will keep the request method
113
- `308 Permanent Redirect`: Redirect will keep the request method, SEO transferred
114
115
**Usage Examples:**
116
117
```typescript
118
import { redirect } from '@sveltejs/kit';
119
120
// In a load function
121
export async function load({ url, locals }) {
122
if (!locals.user) {
123
throw redirect(303, '/login');
124
}
125
126
return { user: locals.user };
127
}
128
129
// In a form action
130
export const actions = {
131
login: async ({ request, cookies }) => {
132
const data = await request.formData();
133
const user = await authenticate(data);
134
135
if (user) {
136
cookies.set('session', user.sessionId, { path: '/' });
137
throw redirect(303, '/dashboard');
138
}
139
140
return fail(400, { message: 'Invalid credentials' });
141
}
142
};
143
144
// Conditional redirects
145
export async function load({ params, url }) {
146
const slug = params.slug;
147
148
if (slug !== slug.toLowerCase()) {
149
throw redirect(301, `/blog/${slug.toLowerCase()}`);
150
}
151
152
return {};
153
}
154
```
155
156
### Redirect Type Guard
157
158
Checks whether an error was thrown by the `redirect()` function.
159
160
```typescript { .api }
161
/**
162
* Checks whether this is a redirect thrown by redirect().
163
* @param e - The object to check
164
* @returns Type predicate indicating if e is a Redirect
165
*/
166
function isRedirect(e: unknown): boolean;
167
```
168
169
**Usage Examples:**
170
171
```typescript
172
import { isRedirect, redirect } from '@sveltejs/kit';
173
174
try {
175
await processRequest();
176
} catch (e) {
177
if (isRedirect(e)) {
178
console.log('Redirect to:', e.location);
179
throw e; // Re-throw to let SvelteKit handle it
180
}
181
182
// Handle other error types
183
console.error('Unexpected error:', e);
184
}
185
```
186
187
## Error Classes
188
189
### HttpError
190
191
The error class thrown by `error()`. Generally you don't construct this directly.
192
193
```typescript { .api }
194
interface HttpError {
195
/** HTTP status code (400-599) */
196
status: number;
197
/** Error content conforming to App.Error */
198
body: App.Error;
199
toString(): string;
200
}
201
```
202
203
### Redirect
204
205
The redirect class thrown by `redirect()`. Generally you don't construct this directly.
206
207
```typescript { .api }
208
interface Redirect {
209
/** HTTP status code (300-308) */
210
status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;
211
/** The location to redirect to */
212
location: string;
213
}
214
```
215
216
## Error Handling Best Practices
217
218
1. **Use appropriate status codes**: 404 for not found, 403 for forbidden, 400 for bad request, etc.
219
2. **Don't catch thrown errors/redirects**: Let SvelteKit handle them unless you need to add logging
220
3. **Provide helpful error messages**: Users and developers should understand what went wrong
221
4. **Use redirects for state changes**: After successful form submissions, use 303 redirects
222
5. **Handle errors at appropriate levels**: Use load functions for page-level errors, endpoints for API errors