Error objects
SvelteKit distinguishes between expected and unexpected errors, both represented as simple{ message: string } objects by default.
Expected errors
An expected error is created with theerror helper from @sveltejs/kit:
src/routes/blog/[slug]/+page.server.js
Displaying errors
src/routes/+error.svelte
Adding custom properties
Shorthand syntax
For convenience, pass a string as the second argument:Unexpected errors
An unexpected error is any other exception that occurs while handling a request. These can contain sensitive information, so messages and stack traces are not exposed to users.handleError hook
Unexpected errors go through thehandleError hook, where you can:
Log errors to a service
Log errors to a service
src/hooks.server.js
Return custom error objects
Return custom error objects
src/hooks.server.js
Handle client errors
Handle client errors
src/hooks.client.js
Make sure that
handleError never throws an error itself.Error responses
How SvelteKit responds to errors depends on where they occur:In handle or +server.js
SvelteKit responds with either:- Fallback error page (if
Acceptheader expects HTML) - JSON representation (if
Acceptheader isapplication/json)
Custom fallback page
Createsrc/error.html to customize the fallback error page:
src/error.html
%sveltekit.status%→ HTTP status code%sveltekit.error.message%→ Error message
In load functions
If an error occurs inside aload function, SvelteKit renders the nearest +error.svelte component.
Error boundary rules
Error boundary rules
- Errors in
+page.server.jsor+page.jsrender the nearest sibling+error.svelte - Errors in
+layout.server.jsor+layout.jsrender the nearest parent+error.svelte(not the sibling) - Errors in root
+layout.jsor+layout.server.jsuse the fallback error page
Type safety
Customize the shape of errors with TypeScript:src/app.d.ts
The
App.Error interface always includes a message: string property.Error helper reference
From@sveltejs/kit:
Throws an HTTP error with a status code and message
Checks if an error was thrown by the
error helperCommon patterns
Learn more
Follow the interactive tutorial on errors and redirects