1

使用 svelte-kit 应用程序并使用 3rd 方 api。

当 api 端点不可用时,try catch 块将捕获错误,此时我可以选择重定向或发回错误和状态。如果发送 404 之类的错误,如果我想显示除普通 404 通用错误页面以外的其他内容,则模板 __error.svelte 需要存在。

来自 sveltekit init 的 todo 演示示例:如果 todos 端点不可用而不是 props 我们返回 {status:404, error: 'Not Found'}。

<script context="module" lang="ts">
    import { enhance } from '$lib/form';
    import type { Load } from '@sveltejs/kit';

    export const load: Load = async ({ fetch }) => {
        try {

            const res = await fetch('/notavailable.json');


            if (res.ok) {
                const todos = await res.json();

                return {
                    props: { todos }
                };
            }


        } catch (error) {

                return {
                    status: 404,
                    error: "Page Not Found"
                };
            
        }

    };
</script>
<h1>Current Page</h2>

如何返回错误消息但仍加载当前页面?(不是重定向或嵌套模板后备,而是留在页面上?)

如果我有一个表格列表,我希望只有标题存在,并且消息将在应用程序的指定区域中。

它接缝我错过了一些东西或重定向,而 __error.svelte 嵌套模板是要走的路吗?

4

1 回答 1

0

我在我的 __error.svelte 模板中发现了一个错误,我不小心留下了……在这个过程中,我想出了如何将错误传递到页面而不是重定向到错误模板。

其实很简单:

  • 如果你想触发默认错误处理程序(__error.svelte)而不是像我在上面的问题中那样返回错误和状态。
  • 如果您仍想继续页面并处理页面中的错误消息而不是返回道具并将错误作为道具传递给组件实例:
    <script context="module" lang="ts">
        import { enhance } from '$lib/form';
        import type { Load } from '@sveltejs/kit';
    
        export const load: Load = async ({ fetch }) => {
            try {
    
                const res = await fetch('/notavailable.json');
    
    
                if (res.ok) {
                    const todos = await res.json();
    
                    return {
                        props: { todos }
                    };
                }
    
    
            } catch (error) {
    
                    return {
                        props: {
                            todos:[],
                            error: {
                                status: 404,
                                error: "Page Not Found"
                            }
                        }
                    };
                
            }
    
        };
    </script>

于 2021-07-24T18:40:46.670 回答