メインコンテンツへスキップ

エラー

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

エラーオブジェクト

SvelteKitは、予期されるエラーと予期しないエラーを区別します。どちらもデフォルトでは単純な{ message: string }オブジェクトとして表現されます。

下記の例のように、codeや追跡idなどの追加プロパティを追加できます。(TypeScriptを使用する場合、型安全性で説明されているように、Error型を再定義する必要があります)。

予期されるエラー

予期されるエラーとは、@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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError 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>>
@type{import('./$types').PageServerLoad}
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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError 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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError 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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError 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がキャッチする例外をスローし、レスポンスステータスコードを404に設定し、+error.svelteコンポーネントをレンダリングします。ここで、$page.errorerror(...)の第2引数として提供されたオブジェクトです。

src/routes/+error
<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.

@paramstatus The HTTP status code. Must be in the range 400-599.
@parambody An object that conforms to the App.Error type. If a string is passed, it will be used as the message property.
@throwsHttpError This error instructs SvelteKit to initiate HTTP error handling.
@throwsError 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' });

…そうでない場合は、便宜上、文字列を第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.

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

SvelteKit 1.xでは、自分でerrorthrowする必要がありました。

予期しないエラー

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

デフォルトでは、予期しないエラーはコンソール(または本番環境ではサーバーログ)に出力され、ユーザーに公開されるエラーは一般的な形状になります。

{ "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).jsload関数内で発生した場合、ツリー内の最寄りのエラー境界は、そのレイアウトの隣ではなく上に位置する+error.svelteファイルになります。

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

型安全性

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プロパティが含まれています。

参考資料

GitHubでこのページを編集する