エラー
エラーはソフトウェア開発において避けられない事実です。SvelteKitは、エラーが発生した場所、エラーの種類、そして着信リクエストの性質に応じて、エラーを異なる方法で処理します。
エラーオブジェクト
SvelteKitは、予期されるエラーと予期しないエラーを区別します。どちらもデフォルトでは単純な{ message: string }
オブジェクトとして表現されます。
下記の例のように、code
や追跡id
などの追加プロパティを追加できます。(TypeScriptを使用する場合、型安全性で説明されているように、Error
型を再定義する必要があります)。
予期されるエラー
予期されるエラーとは、@sveltejs/kit
からインポートされたerror
ヘルパーを使用して作成されたエラーです。
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.
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.
error(404, {
App.Error.message: string
message: '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.
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: PageServerLoad
load: 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.
error(404, {
App.Error.message: string
message: 'Not found'
});
}
return { post: {
title: string;
content: string;
}
post };
};
これはSvelteKitがキャッチする例外をスローし、レスポンスステータスコードを404に設定し、+error.svelte
コンポーネントをレンダリングします。ここで、$page.error
はerror(...)
の第2引数として提供されたオブジェクトです。
<script>
import { page } from '$app/stores';
</script>
<h1>{$page.error.message}</h1>
必要に応じて、エラーオブジェクトに追加のプロパティを追加できます…
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.
error(404, {
App.Error.message: string
message: 'Not found',
App.Error.code: string
code: 'NOT_FOUND'
});
…そうでない場合は、便宜上、文字列を第2引数として渡すことができます。
error(404, { message: '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.
error(404, 'Not found');
SvelteKit 1.xでは、自分で
error
をthrow
する必要がありました。
予期しないエラー
予期しないエラーとは、リクエストの処理中に発生するその他の例外です。これらには機密情報が含まれる可能性があるため、予期しないエラーメッセージとスタックトレースはユーザーに公開されません。
デフォルトでは、予期しないエラーはコンソール(または本番環境ではサーバーログ)に出力され、ユーザーに公開されるエラーは一般的な形状になります。
{ "message": "Internal Error" }
予期しないエラーはhandleError
フックを通過します。ここで、独自のエラー処理を追加できます。たとえば、エラーをレポートサービスに送信したり、$page.error
になるカスタムエラーオブジェクトを返したりできます。
レスポンス
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).js
のload
関数内で発生した場合、ツリー内の最寄りのエラー境界は、そのレイアウトの隣ではなく上に位置する+error.svelte
ファイルになります。
例外は、ルート+layout.js
または+layout.server.js
内でエラーが発生した場合です。ルートレイアウトは通常+error.svelte
コンポーネントを含むためです。この場合、SvelteKitはフォールバックエラーページを使用します。
型安全性
TypeScriptを使用していて、エラーの形状をカスタマイズする必要がある場合は、アプリにApp.Error
インターフェースを宣言することで実行できます(慣例ではsrc/app.d.ts
ですが、TypeScriptが認識できる場所であればどこにでも配置できます)。
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: string
code: string;
App.Error.id: string
id: string;
}
}
}
export {};
このインターフェースには常にmessage: string
プロパティが含まれています。