Skip to main content

Errors

ソフトウェア開発において、エラーは避けられないものです。SvelteKit では、エラーが発生した場所、エラーの種類、受信したリクエストの性質に応じて、異なる方法でエラーを処理します。

Error objects

SvelteKit は想定されるエラーと予期せぬエラーを区別します。どちらもデフォルトではシンプルな { message: string } オブジェクトとして表現されます。

以下の例のように、code やトラッキング id を追加することができます。(TypeScript を使用する場合、Type safety で説明したように Error 型を再定義する必要があります)

Expected errors

想定されるエラーとは、@sveltejs/kit からインポートされる error を使用して作成されるものを指します:

src/routes/blog/[slug]/+page.server
import { function error(status: number, body: App.Error): never (+1 overload)

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.

@param
status The HTTP status code. Must be in the range 400-599.
@param
body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throws
HttpError This error instructs SvelteKit to initiate HTTP error handling.
@throws
Error If the provided status is invalid (not between 400 and 599).
error
} from '@sveltejs/kit';
import * as module "$lib/server/database"db from '$lib/server/database'; /** @type {import('./$types').PageServerLoad} */ export async function function load(event: ServerLoadEvent<Record<string, any>, Record<string, any>, string | null>): MaybePromise<void | Record<string, any>>load({ params: Record<string, any>

The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.

params
}) {
const
const post: {
    title: string;
    content: string;
} | undefined
post
= await module "$lib/server/database"db.
function getPost(slug: string): Promise<{
    title: string;
    content: string;
} | undefined>
getPost
(params: Record<string, any>

The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.

params
.slug);
if (!
const post: {
    title: string;
    content: string;
} | undefined
post
) {
function error(status: number, body: App.Error): never (+1 overload)

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.

@param
status The HTTP status code. Must be in the range 400-599.
@param
body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throws
HttpError This error instructs SvelteKit to initiate HTTP error handling.
@throws
Error If the provided status is invalid (not between 400 and 599).
error
(404, {
App.Error.message: stringmessage: 'Not found' }); } return {
post: {
    title: string;
    content: string;
}
post
};
}
import { function error(status: number, body: App.Error): never (+1 overload)

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.

@param
status The HTTP status code. Must be in the range 400-599.
@param
body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throws
HttpError This error instructs SvelteKit to initiate HTTP error handling.
@throws
Error If the provided status is invalid (not between 400 and 599).
error
} from '@sveltejs/kit';
import * as module "$lib/server/database"db from '$lib/server/database'; import type { type PageServerLoad = (event: ServerLoadEvent<Record<string, any>, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>PageServerLoad } from './$types'; export const const load: PageServerLoadload: type PageServerLoad = (event: ServerLoadEvent<Record<string, any>, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>PageServerLoad = async ({ params: Record<string, any>

The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.

params
}) => {
const
const post: {
    title: string;
    content: string;
} | undefined
post
= await module "$lib/server/database"db.
function getPost(slug: string): Promise<{
    title: string;
    content: string;
} | undefined>
getPost
(params: Record<string, any>

The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.

params
.slug);
if (!
const post: {
    title: string;
    content: string;
} | undefined
post
) {
function error(status: number, body: App.Error): never (+1 overload)

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.

@param
status The HTTP status code. Must be in the range 400-599.
@param
body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throws
HttpError This error instructs SvelteKit to initiate HTTP error handling.
@throws
Error If the provided status is invalid (not between 400 and 599).
error
(404, {
App.Error.message: stringmessage: 'Not found' }); } return {
post: {
    title: string;
    content: string;
}
post
};
};

これは SvelteKit が catch する例外をスローし、それによってレスポンスのステータスコードを 404 に設定し、+error.svelte コンポーネントをレンダリングします。page.errorerror(...) に第二引数として渡されたオブジェクトです。

src/routes/+error
<script>
	import { page } from '$app/state';
</script>

<h1>{page.error.message}</h1>
<script lang="ts">
	import { page } from '$app/state';
</script>

<h1>{page.error.message}</h1>
Legacy mode

$app/state was added in SvelteKit 2.12. If you're using an earlier version or are using Svelte 4, use $app/stores instead.

必要に応じて、エラーオブジェクトにプロパティを追加することができます…

function error(status: number, body: App.Error): never (+1 overload)

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.

@param
status The HTTP status code. Must be in the range 400-599.
@param
body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throws
HttpError This error instructs SvelteKit to initiate HTTP error handling.
@throws
Error If the provided status is invalid (not between 400 and 599).
error
(404, {
App.Error.message: stringmessage: 'Not found', App.Error.code: stringcode: 'NOT_FOUND' });

…追加しない場合は、便宜上、文字列を第二引数に渡すことができます:

                                     
function error(status: number, body?: {
    message: string;
} extends App.Error ? App.Error | string | undefined : never): never (+1 overload)

Throws an error with a HTTP status code and an optional message. When called during request handling, this will cause SvelteKit to return an error response without invoking handleError. Make sure you're not catching the thrown error, which would prevent SvelteKit from handling it.

@param
status The HTTP status code. Must be in the range 400-599.
@param
body An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throws
HttpError This error instructs SvelteKit to initiate HTTP error handling.
@throws
Error If the provided status is invalid (not between 400 and 599).
error
(404, 'Not found');

SvelteKit 1.x 系では、ご自身で errorthrow しなければいけませんでした。

Unexpected errors

予期せぬエラーとは、リクエストの処理中に発生するその他の例外のことを指します。これらは機密情報を含むことがあるため、予期せぬエラーのメッセージとスタックトレースはユーザーには公開されません。

デフォルトでは、予期せぬエラーはコンソール (または、本番環境では、サーバーログ) に出力され、ユーザーに公開されるエラーはこのように汎用的な形式です。

{ "message": "Internal Error" }

Unexpected errors will go through the handleError hook, where you can add your own error handling — for example, sending errors to a reporting service, or returning a custom error object which becomes page.error.

Rendering errors

Ordinarily, if an error happens during server-side rendering (for example inside a component's <script> block or template), SvelteKit will return a 500 error page.

Since SvelteKit 2.54 and Svelte 5.53, you can change this by enabling the experimental handleRenderingErrors option in your config:

svelte.config
/** @type {import('@sveltejs/kit').Config} */
const const config: Configconfig = {
	Config.kit?: KitConfig | undefined

SvelteKit options.

kit
: {
KitConfig.experimental?: {
    tracing?: {
        server?: boolean;
    };
    instrumentation?: {
        server?: boolean;
    };
    remoteFunctions?: boolean;
    forkPreloads?: boolean;
    handleRenderingErrors?: boolean;
} | undefined

Experimental features. Here be dragons. These are not subject to semantic versioning, so breaking changes or removal can happen in any release.

experimental
: {
handleRenderingErrors?: boolean | undefined

Whether to enable the experimental handling of rendering errors. When enabled, <svelte:boundary> is used to wrap components at each level where there's an +error.svelte, rendering the error page if the component fails. In addition, error boundaries also work on the server and the error object goes through handleError.

@default
false
handleRenderingErrors
: true
} } }; export default const config: Config
config
;

When this is enabled, SvelteKit will wrap your route components in an error boundary. If an error occurs during rendering, the nearest +error.svelte page will be shown, just as if the error had occurred in a load function.

The error is first passed to handleError, allowing you to report it and transform it, before the resulting object is passed to the +error.svelte component.

Since rendering errors occur after the page has started rendering, and multiple boundaries could in parallel catch distinct errors, the page object (and its error property) will not be updated. Instead, the error is passed directly to the +error.svelte component as a prop.

+error
<script>
	let { error } = $props();
</script>

<h1>{error.message}</h1>
<script lang="ts">
	let { error } = $props();
</script>

<h1>{error.message}</h1>

The same applies for other error boundaries you define in your code:

<svelte:boundary>
	...
	{#snippet failed(error: App.Error)}
		<!-- error went through handleError and is of type App.Error -->
		{error.message}
	{/snippet}
</svelte:boundary>

Responses

もし handle の中や +server.js リクエストハンドラの中でエラーが発生した場合、SvelteKit はリクエストの Accept ヘッダー に応じて、フォールバックエラーページか、エラーオブジェクトの JSON 表現をレスポンスとして返します。

src/error.html ファイルを追加することで、フォールバックエラーページをカスタマイズすることができます:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>%sveltekit.error.message%</title>
	</head>
	<body>
		<h1>My custom error page</h1>
		<p>Status: %sveltekit.status%</p>
		<p>Message: %sveltekit.error.message%</p>
	</body>
</html>

SvelteKit が %sveltekit.status%%sveltekit.error.message% を、それぞれ対応する値に置き換えます。

ページのレンダリング中に load 関数の中でエラーが発生した場合、SvelteKit はエラーが発生した場所に最も近い +error.svelte コンポーネントをレンダリングします。+layout(.server).jsload 関数の内側でエラーが発生した場合、ツリーの中で最も近くにあるエラー境界はそのレイアウトの上位にある +error.svelte ファイルです (隣ではありません)。

例外は、最上位の +layout.js+layout.server.js の中でエラーが発生した場合です。通常、最上位のレイアウトには +error.svelte コンポーネントが含まれているためです。この場合、SvelteKit はフォールバックエラーページを使用します。

Type safety

もし TypeScript を使用していてエラーの形式をカスタマイズする必要がある場合、アプリで App.Error インターフェイスを宣言することでそれができます (慣習ではこれを src/app.d.ts に書きますが、TypeScript が '参照' することができればどこでも構いません):

src/app.d
declare global {
	namespace App {
		interface interface App.Error

Defines the common shape of expected and unexpected errors. Expected errors are thrown using the error function. Unexpected errors are handled by the handleError hooks which should return this shape.

Error
{
App.Error.code: stringcode: string; App.Error.id: stringid: string; } } } export {};

このインターフェイスは常に message: string プロパティを含んでいます。

その他の参考資料

Edit this page on GitHub llms.txt

previous next