How to handle errors in SvelteKit

Handling errors is easy. Just call error()

Backstory:

I wanted the sitemap route to work both on sitemap.xml and sitemap_index.xml — partly the same code, no duplication. Note that the end result these pages return, is not the same for both. But I digress.

To achieve that, I first renamed src/routes/sitemap.xml to src/routes/[slug].xml

Then modified the sitemap code at (now) src/routes/[slug].xml/+server.js to ensure that slug is sitemap or sitemap_index:

import { error } from "@sveltejs/kit"
...
export const GET = async ({ params }) => {
  const slug = params.slug

  if (![ "sitemap", "sitemap_index" ].includes(slug)) {
    error(404)
  }
  ...

Notice the call to error(404) which will throw an exception, stop the execution, and leads to a 404 page in the browser.