跳至主要内容

错误

错误是软件开发中不可避免的事实。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.error 是作为 error(...) 的第二个参数提供的对象。

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' });

...否则,为了方便起见,您可以将字符串作为第二个参数传递。

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 中,您必须自己 throw error

意外错误

意外错误是在处理请求期间发生的任何其他异常。由于这些错误可能包含敏感信息,因此不会向用户公开意外错误消息和堆栈跟踪。

默认情况下,意外错误会打印到控制台(或在生产环境中打印到服务器日志),而公开给用户的错误具有通用形状。

{ "message": "Internal Error" }

意外错误将通过 handleError 钩子,您可以在其中添加自己的错误处理 - 例如,将错误发送到报告服务,或返回自定义错误对象,该对象将成为 $page.error

响应

如果错误发生在 handle 内部或 +server.js 请求处理程序内部,SvelteKit 将响应回退错误页面或错误对象的 JSON 表示形式,具体取决于请求的 Accept 标头。

您可以通过添加 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 可以“看到”的任何地方)。

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 上编辑此页面

上一页 下一页