9

The documentation seems a bit vague about showing the error page from Hooks. I am looking for a way to show the 404 page conditionally.

export async function handle({ event, resolve }) {
  return new Response('This page does not exist.', {status: 404})
}

This returns a status 404 page in a plain text, but I want it to return an error page with a layout, not just text. Is there any API to use? Or should I redirect to the 404 page?

yongju lee
  • 564
  • 1
  • 4
  • 16
  • 1
    do you have an answer afterall? – LazNiko Jul 31 '22 at 14:29
  • 2
    @LazNiko I couldn't find the right solution, from the documentation, nor from the community & web. I just ended up redirecting to the 404 page if the request is not valid. ex) return new Response('This page does not exist.', {status: 302, headers: { Location: '/404' }}) – yongju lee Aug 08 '22 at 02:31
  • 1
    understood. that would be a solution. thank you. – LazNiko Aug 09 '22 at 19:27

1 Answers1

0

There may be a better way, but you can set the event.route so that the resolve function will return the error page:

export const handle = (async ({ event, resolve }) => {
  if (shouldBeNotFound(event)) {
    event.route = {id: null};
  }
 
  const response = await resolve(event);
  return response;
}) satisfies Handle;

This will lead resolve to think that the page did not match any route of your app, and to render your topmost +error.svelte.

Cédric Van Rompay
  • 2,489
  • 1
  • 18
  • 24