handleError
钩子可让你拦截意外错误并触发某些行为,例如 ping Slack 通道或将数据发送到错误日志服务。
¥The handleError
hook lets you intercept unexpected errors and trigger some behaviour, like pinging a Slack channel or sending data to an error logging service.
正如你从 早期练习 中记得的那样,如果不是使用 @sveltejs/kit
中的 error
助手创建的,则错误是意外的。它通常意味着你的应用中需要修复某些内容。默认行为是记录错误:
¥As you’ll recall from an earlier exercise, an error is unexpected if it wasn’t created with the error
helper from @sveltejs/kit
. It generally means something in your app needs fixing. The default behaviour is to log the error:
export function handleError({ event, error }) {
console.error(error.stack);
}
如果你导航到 /the-bad-place
,你将看到此操作 - 显示错误页面,如果你打开终端(使用 URL 栏右侧的按钮),你将看到来自 src/routes/the-bad-place/+page.server.js
的消息。
¥If you navigate to /the-bad-place
, you’ll see this in action — the error page is shown, and if you open the terminal (using the button to the right of the URL bar), you’ll see the message from src/routes/the-bad-place/+page.server.js
.
请注意,我们不会向用户显示错误消息。这是因为错误消息可能包含敏感信息,这些信息充其量会让你的用户感到困惑,最坏的情况可能会让作恶者受益。相反,你的应用可用的错误对象(在你的 +error.svelte
页面中表示为 page.error
,或在你的 src/error.html
后备中表示为 %sveltekit.error%
)就是这样:
¥Notice that we’re not showing the error message to the user. That’s because error messages can include sensitive information that at best will confuse your users, and at worst could benefit evildoers. Instead, the error object available to your application — represented as page.error
in your +error.svelte
pages, or %sveltekit.error%
in your src/error.html
fallback — is just this:
{
message: 'Internal Error' // or 'Not Found' for a 404
}
在某些情况下,你可能想要自定义此对象。为此,你可以从 handleError
返回一个对象:
¥In some situations you may want to customise this object. To do so, you can return an object from handleError
:
export function handleError({ event, error }) {
console.error(error.stack);
return {
message: 'everything is fine',
code: 'JEREMYBEARIMY'
};
}
你现在可以在自定义错误页面中引用除 message
之外的属性。创建 src/routes/+error.svelte
:
¥You can now reference properties other than message
in a custom error page. Create src/routes/+error.svelte
:
<script>
import { page } from '$app/state';
</script>
<h1>{page.status}</h1>
<p>{page.error.message}</p>
<p>error code: {page.error.code}</p>
<script lang="ts">
import { page } from '$app/state';
</script>
<h1>{page.status}</h1>
<p>{page.error.message}</p>
<p>error code: {page.error.code}</p>
<h1>home</h1>