Errors
错误是软件开发不可避免的事实。SvelteKit 根据错误发生的位置、错误类型以及请求的性质来处理错误。
错误对象
SvelteKit 区分预期错误和意外错误,这两者默认都表示为简单的 { message: string } 对象。
您可以添加额外的属性,例如一个 代码 或一个跟踪的 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: 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.
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.
error(404, {
App.Error.message: stringmessage: 'Not found'
});
}
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>[!旧版]
$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: 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.
[!注意] 在 SvelteKit 1.x 中您必须
抛出错误自己
意外错误
一个 意外 错误是在处理请求时发生的任何其他异常。由于这些可能包含敏感信息,意外错误消息和堆栈跟踪不会向用户公开。
默认情况下,意外错误会被打印到控制台(或者在生产环境中,你的服务器日志中),而暴露给用户的错误具有通用的形状:
{ "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.ErrorDefines 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