Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

SvelteKit 中有两种类型的错误 - 预期错误和意外错误。

¥There are two types of errors in SvelteKit — expected errors and unexpected errors.

预期错误是通过 @sveltejs/kit 中的 error 辅助程序抛出的错误,如 src/routes/expected/+page.server.js 中所示:

¥An expected error is one that was thrown via the error helper from @sveltejs/kit, as in src/routes/expected/+page.server.js:

src/routes/expected/+page.server
import { error } from '@sveltejs/kit';

export function load() {
	error(420, 'Enhance your calm');
}

任何其他错误(例如 src/routes/unexpected/+page.server.js 中的错误)都被视为意外错误:

¥Any other error — such as the one in src/routes/unexpected/+page.server.js — is treated as unexpected:

src/routes/unexpected/+page.server
export function load() {
	throw new Error('Kaboom!');
}

当你抛出一个预期的错误时,你是在告诉 SvelteKit ‘别担心,我知道我的意思’m 正在这里做’。相比之下,意外错误则被认为是应用中的一个错误。当出现意外错误时,其消息和堆栈跟踪将记录到控制台。

¥When you throw an expected error, you’re telling SvelteKit ‘don’t worry, I know what I’m doing here’. An unexpected error, by contrast, is assumed to be a bug in your app. When an unexpected error is thrown, its message and stack trace will be logged to the console.

在后面的章节中,我们将学习如何使用 handleError 钩子添加自定义错误处理。

¥[!NOTE] In a later chapter we’ll learn about how to add custom error handling using the handleError hook.

如果你单击此应用中的链接,你会注意到一个重要的区别:预期的错误消息显示给用户,而意外的错误消息被编辑并替换为通用 ‘内部错误’ 消息和 500 状态代码。这是因为错误消息可能包含敏感数据。

¥If you click the links in this app, you’ll notice an important difference: the expected error message is shown to the user, whereas the unexpected error message is redacted and replaced with a generic ‘Internal Error’ message and a 500 status code. That’s because error messages can contain sensitive data.

上一页 下一页
1
2
<h1>home</h1>