如何在 SvelteKit 中添加自定义 404 页面和不同的错误页面(用于其他错误)?
How to add a custom 404 page and a different Error page (for other errors) in SvelteKit?
基本上,如何做ff。在 SvelteKit 中:
- 首先添加自定义 404 页面。
- 有一个不同的通用错误页面,该页面将显示 message/description 关于 SvelteKit 中的错误
通读 docs 后,我找到了答案并在下面创建了更具体的步骤来实现我喜欢的目标:
- 在您的 routes 文件夹中创建
__error.svelte
。
- 在该文件中,您可以按照 docs:
中所示执行此操作
<script context="module">
export function load({ error, status }) {
return {
props: {
title: `${status}: ${error.message}`
}
};
}
</script>
<script>
export let title;
</script>
<h1>{title}</h1>
- 我们还没有完成!您可以检查状态代码,然后呈现不同的屏幕组件。 (顺便在
load
函数里面配置props
:
<script context="module">
export function load({ error, status }) {
return {
props: {
message: error.message,
status // same as status: status
}
};
}
</script>
<script>
import ErrorScreen from '../components/screens/ErrorScreen.svelte'; // your own Error screen component
import NotFoundScreen from '../components/screens/NotFoundScreen.svelte'; // your own 404 screen component
export let message;
export let status;
</script>
{#if status == 404} <!-- Used '==' instead of '===' to match string/number status code (just to be sure) -->
<NotFoundScreen />
{:else}
<ErrorScreen {message} {status} />
{/if}
- 大功告成!您可以通过将
#if status == 404
更改为喜欢 #if status == 500
来测试它,看看是否一切正常。 (不要忘记将其改回 404
)。
基本上,如何做ff。在 SvelteKit 中:
- 首先添加自定义 404 页面。
- 有一个不同的通用错误页面,该页面将显示 message/description 关于 SvelteKit 中的错误
通读 docs 后,我找到了答案并在下面创建了更具体的步骤来实现我喜欢的目标:
- 在您的 routes 文件夹中创建
__error.svelte
。 - 在该文件中,您可以按照 docs: 中所示执行此操作
<script context="module"> export function load({ error, status }) { return { props: { title: `${status}: ${error.message}` } }; } </script> <script> export let title; </script> <h1>{title}</h1>
- 我们还没有完成!您可以检查状态代码,然后呈现不同的屏幕组件。 (顺便在
load
函数里面配置props
:
<script context="module"> export function load({ error, status }) { return { props: { message: error.message, status // same as status: status } }; } </script> <script> import ErrorScreen from '../components/screens/ErrorScreen.svelte'; // your own Error screen component import NotFoundScreen from '../components/screens/NotFoundScreen.svelte'; // your own 404 screen component export let message; export let status; </script> {#if status == 404} <!-- Used '==' instead of '===' to match string/number status code (just to be sure) --> <NotFoundScreen /> {:else} <ErrorScreen {message} {status} /> {/if}
- 大功告成!您可以通过将
#if status == 404
更改为喜欢#if status == 500
来测试它,看看是否一切正常。 (不要忘记将其改回404
)。