错误处理
错误是软件开发中不可避免的事实。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: '未找到'
});
}
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: '未找到'
});
}
return { post: {
title: string;
content: string;
}
post };
};
这会抛出一个异常,SvelteKit 会捕获该异常,并将响应状态码设置为 404,并渲染一个 +error.svelte
组件,其中 page.error
是一个对象,提供给 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
是在 SvelteKit 2.12 中添加的。如果您使用的是早期版本或正在使用 Svelte 4,请使用$app/stores
代替。
如果需要,您可以向错误对象添加额外的属性...
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: '未找到',
App.Error.code: string
code: 'NOT_FOUND'
});
...否则,为了方便起见,您可以将字符串作为第二个参数传递:
error(404, { message: '未找到' });
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.
在 SvelteKit 1.x 中,您必须自己
throw
这个error
意外错误
意外错误是处理请求时发生的任何其他异常。由于这些错误可能包含敏感信息,意外错误消息和堆栈跟踪不会暴露给用户。
默认情况下,意外错误会打印到控制台(或在生产环境中打印到服务端日志),而暴露给用户的错误具有通用的形状:
{ "message": "内部错误" }
意外错误将通过 handleError
hook 处理,在那里您可以添加自己的错误处理逻辑 — 例如,将错误发送到报告服务,或返回一个自定义错误对象,该对象将成为 $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>我的自定义错误页面</h1>
<p>状态:%sveltekit.status%</p>
<p>消息:%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
属性。