Home > OS >  Error not properly passing message in sveltekit
Error not properly passing message in sveltekit

Time:01-27

I am having an issue where sveltekit error function found at this link is not passing message correctly. See below code for example. The css classes are windicss classes.

Here is my page.server.ts

import { error } from '@sveltejs/kit'
import type { PageServerLoad } from './$types'

export const load: PageServerLoad = ({ url }) => {
  throw error(404, {
    message: 'Not found',
    code: 'NOT_FOUND'
  })
}

Here is the error.svelte page

<script lang="ts">
  import { page } from '$app/stores'
  import turtle from '$images/error/turtle-optimized.webp'
</script>

<section >
  <div >
    <h1>
      {$page.status}
      {#if $page.error}
        <!-- Debugging line below -->
        {JSON.stringify($page.error)}
        : {$page.error.message}
      {/if}
    </h1>
  </div>
  <span >
    <a href="/" > Home </a>
    <a href="/shop" > Shop </a>
  </span>
  <span >
    <img  width="400rem" src={turtle} alt="Sea turtle" />
  </span>
</section>

I have tried to pass the message to the error page and display using

JSON.stringify($page.error)

the value that is displayed is

{"message":"Error: 404"}

I expect the value for

JSON.stringify($page.error)

to be

{"message":"Not Found"}

CodePudding user response:

You haven't specified whether or not you have a corresponding page.svelte file for the page.server.ts, but if you don't my guess is that SvelteKit will throw its own 404 error if you don't handle it, and that is taking precedence over your own. Additionally, I'm pretty sure that any error inside a page.server.ts will simply pass as either a default 404 or a vague Internal Error before being passed to the client. Perhaps take a look at the SvelteKit Docs for some more info on this. How you handle your error will depend on your specific situation, so more info on what you are trying to accomplish would be great.

  • Related