Skip to content

@ogygia/router

Error handling

redirect() and error() are thrown from a load, action or handler, as in Kit. A page's error renders the nearest error page inside the layouts that still work, an endpoint's error answers JSON, and miss decides what an unmatched path under the table's base gets.

On this page

A post that doesn’t exist, a visitor who isn’t signed in, a page that moved: a load often finds out it can’t go on. A load, action or handler stops early by throwing. redirect(status, location) sends the visitor somewhere else. error(status, message) ends the request with an error. Both have Kit’s names and arguments, and both come from @ogygia/router. fail(status, data) is the third, for form actions, and it’s returned, not thrown.

import { routes, page, error, redirect } from '@ogygia/router';
import Post from '$lib/views/Post.svelte';
import { posts } from '$lib/server/posts';

export const router = routes({
  '/posts/[slug]': page(Post, {
    load: async (c) => {
      const post = await posts.get(c.params.slug);
      if (!post) error(404, 'No such post');
      if (post.movedTo)
        redirect(308, `/posts/${post.movedTo}`);
      return { post };
    }
  })
});

Redirects

redirect(status, location) answers with that status and a location header, and cache-control: no-store. location can be a string or a URL. Use 303 after a form post, 307 or 308 to keep the method, 302 or 301 otherwise. The status is sent as you give it: unlike Kit, the router doesn’t check it’s a 3xx. Nor does error() check its status is a 4xx or 5xx (#2293).

The SPA router follows a redirect within your site without a full page load.

Error pages

An error() thrown on a page’s branch renders an error page, the router’s +error.svelte. You set them on the table and on layouts:

  • routes(table, { error: ErrorPage }) is the root error page.
  • layout(name, Shell, { error: ShellError }) is the error page for the routes inside that layout.

Which error page renders

Which page renders mostly follows Kit’s rules; the data it gets doesn’t. A layout’s error page renders inside that layout and the layouts above it, so the visitor keeps your header and navigation:

  • An error from the page’s load or an action renders the nearest error page: that of the innermost layout that has one, else the root one. It renders inside every layout up to the one that owns it.
  • An error from a layout’s load skips that layout’s own error page, since the layout couldn’t load. The nearest error page above it renders, inside the layouts above that error page. If no layout above has one, the root error page renders, with no layout.
  • An error from the table-wide load renders the root error page, with no layout.
  • With no error page on the way, the request answers JSON: { "error": message, "status": status }.

The response has the error’s status.

The root error page always renders with no layout, even when every layout’s load succeeded. In Kit, the root +error.svelte sits inside the root layout; here it doesn’t. To keep your shell on errors, give the outermost layout an error of its own.

What data the error page gets

To fill in the error page, the router runs every load on the page’s branch: the table-wide load, every layout’s and the page’s own, including loads that hadn’t started when the error was thrown. A load that already ran isn’t run twice. The error page and its layouts get the merged data of every load that succeeded, from below the error page’s layout too. Kit gives an error page only the data of the layouts above it (#2294). So a guard shouldn’t turn visitors away with error() yet; see Guard every route for why, and what to do instead.

Write an error page

An error page is a component. It gets these props:

PropWhat it holds
statusThe error’s status, like 404.
error{ message }, the message given to error(), 'Error' if none.
dataThe merged data of every load on the branch that succeeded. See above.
paramsThe route’s params.

page.status and page.error from $app/state hold the same values, so an island on the error page can read them.

import { routes, page, layout } from '@ogygia/router';
import Shell from '$lib/views/Shell.svelte';
import ShellError from '$lib/views/ShellError.svelte';
import RootError from '$lib/views/RootError.svelte';
import Post from '$lib/views/Post.svelte';
import { posts } from '$lib/server/posts';

const app = layout('app', Shell, {
  error: ShellError
});

export const router = routes(
  app({
    '/posts/[slug]': page(Post, {
      load: async (c) => ({
        post: await posts.get(c.params.slug)
      })
    })
  }),
  { error: RootError }
);
<script lang="ts">
  interface Props {
    status: number;
    error: { message: string };
  }
  let { status, error }: Props = $props();
</script>

<svelte:head><title>{status}</title></svelte:head>

<h1>{status}</h1>
<p>{error.message}</p>
<a href="/">Back home</a>

Endpoint errors

An endpoint has no error page. error(status, message) there answers JSON, { "error": message, "status": status }, with that status. The typed client throws it as an ApiError with that object as its body.

Uncaught errors

Only the router’s own error() and redirect() are caught. Anything else thrown, a plain Error or a database failure, leaves the table. Kit then answers as for any failure in a hook: it calls your handleError and sends its static error page (src/error.html) with status 500, or JSON to a request that asks for it. Your router error pages don’t render.

Kit’s own error() from @sveltejs/kit isn’t caught either. Kit answers it with its static error page at that error’s status, so it skips your router error pages: import error from @ogygia/router in table code. Kit’s own redirect() is also left to Kit, which answers it as a redirect; that has one use today, setting a cookie from the hook.

When your code catches errors around a call that may throw one of these, rethrow them. isRedirect(e) and isHttpError(e) from @ogygia/router know only the router’s own; rethrow Kit’s too, with Kit’s isRedirect, if your code uses Kit’s redirect() for cookies.

import { isHttpError, isRedirect } from '@ogygia/router';
import { isRedirect as isKitRedirect } from '@sveltejs/kit';

export async function orNull<T>(
  work: () => Promise<T>
): Promise<T | null> {
  try {
    return await work();
  } catch (e) {
    if (isRedirect(e) || isHttpError(e) || isKitRedirect(e))
      throw e;
    return null;
  }
}

Not found

What happens to a path no key matches depends on whether the table has a base:

  • Without a base, the table doesn’t answer. router.handle passes the request on to the rest of your app, Kit’s routes included, and router.fetch returns null.
  • With a base, a path outside it is passed on the same way. A path under it is the table’s to answer, and it does so in this order:
    1. With a miss option, miss(c) answers, like an endpoint.
    2. Otherwise, a browser asking for a page (GET or HEAD, accepting text/html) gets the root error page with status 404 and the message Not found, when the table has one.
    3. Otherwise, a plain-text 404 Not found.

A route turned off by when() counts as unmatched for that request.

Answer unmatched paths with miss

miss(c) answers the way a handler does: a returned Response is sent as it is, another value is sent as JSON, a thrown redirect() redirects, and a thrown error() answers JSON with its status. It runs for every method. Its c has empty params, and c.route.id is ''. Unlike a handler’s, headers it sets with c.setHeaders() don’t reach the response when the table is served from the hook (#2293); put them on the Response it returns.

miss has no effect without a base.

import { routes, page, redirect } from '@ogygia/router';
import Home from '$lib/views/Home.svelte';

export const router = routes(
  { '/': page(Home) },
  {
    base: '/shop',
     miss: (c) =>
      redirect(
        307,
        c.url.pathname.replace('/shop', '/store')
      ) 
  }
);

Failure responses

What happenedThe answer
error() on a page’s branchThe nearest error page, with the error’s status, or JSON when there’s none.
error() in an endpoint or missJSON { error, status }, with the error’s status.
redirect() anywhereThe redirect, with cache-control: no-store.
A path that fails the page’s params schemaPlain-text 404 Not found. No error page renders. The page’s and layouts’ loads don’t run (the table-wide load already has).
A query that fails the page’s search schema400 JSON { error: 'Invalid query', issues }. The page’s and layouts’ loads don’t run.
A body that fails an endpoint’s schema400 JSON { error: 'Invalid body', issues }, or { error: 'Invalid JSON body' }.
A verb the page or endpoint doesn’t take405, with an Allow header. An OPTIONS request gets 204 with that header.
A post to an action the page doesn’t have404 through the nearest error page.
A path with the wrong trailing slash308 to the right one, query kept.
A streamed page that yields nothing500 through the nearest error page.
An unmatched path under basemiss, the root error page, or a 404.
Any other throwKit’s error page: 500, or the status of a Kit error().