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
:
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:
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.
<h1>home</h1>