Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

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.

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:

src/hooks.server
export function handleError({ event, error }) {
	console.error(error.stack);
}

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.

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
}

In some situations you may want to customise this object. To do so, you can return an object from handleError:

src/hooks.server
export function handleError({ event, error }) {
	console.error(error.stack);

	return {
		message: 'everything is fine',
		code: 'JEREMYBEARIMY'
	};
}

You can now reference properties other than message in a custom error page. Create src/routes/+error.svelte:

src/routes/+error
<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>

Edit this page on GitHub

previous next
1
<h1>home</h1>