【问题标题】:How to add a custom 404 page and a different Error page (for other errors) in SvelteKit?如何在 SvelteKit 中添加自定义 404 页面和不同的错误页面(针对其他错误)?
【发布时间】:2021-11-18 03:32:23
【问题描述】:

基本上,如何做ff。在 SvelteKit 中:

  • 先添加自定义 404 页面。
  • 有一个不同的通用错误页面,该页面将显示有关 SvelteKit 中错误的消息/描述

【问题讨论】:

    标签: svelte sveltekit


    【解决方案1】:

    通读docs后,我找到了答案,并在下面创建了更具体的步骤来实现我喜欢的:

    1. 在您的 routes 文件夹中创建 __error.svelte
    2. 在该文件中,您可以按照docs 中所示执行此操作:
    <script context="module">
      export function load({ error, status }) {
          return {
              props: {
                  title: `${status}: ${error.message}`
              }
          };
      }
    </script>
    
    <script>
      export let title;
    </script>
    
    <h1>{title}</h1>
    
    1. 我们还没有完成!您可以检查状态代码,然后渲染不同的屏幕组件。 (顺便说一下,你可以在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}
    
    1. 一切就绪!您可以通过将#if status == 404 更改为喜欢#if status == 500 来测试它,看看是否一切正常。 (别忘了改回404)。

    【讨论】:

    • 您还需要在 ErrorScreen 中包含状态,否则: '{ message: any; 类型中缺少属性 'status' }' 但在 '{ message: any; 类型中是必需的状态:任何; }'
    • 有没有办法打印整个跟踪?例如,错误发生在哪个行号/文件等?
    猜你喜欢
    • 2019-11-28
    • 1970-01-01
    • 2016-04-25
    • 2013-09-16
    • 2015-03-18
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 2014-08-06
    相关资源
    最近更新 更多