Skip to content

Allow error pages with json bodies #1931

@Astavie

Description

@Astavie

Describe the problem

I'm making a full-stack website in SvelteKit, and am now working on my API. This api is located under /api/*. When a user requests from an unknown URI I want to send a 404 message. As the API responds with json, I would like to respond in the same manner with the error message. However, to my knowledge, __error.svelte files only support html as an output.

Describe the proposed solution

I can see two solutions

  1. implementation of an __error.json file
  2. an export in endpoints that get executed on all undefined http methods

I prefer number 2, as then I could also implement 405 Method Not Allowed errors.

Alternatives considered

For now, I'm using an endpoint like this:

function response() { return {
    status: 404,
    body: {
        "error": "notfound",
        "message": "Not Found"
    }
}}

// Most HTTP request methods
export const get = response;
export const post = response;
export const put = response;
export const patch = response;
export const del = response;
export const options = response;
export const head = response;

this is located under src/routes/api/[...error].ts

Although this works, it's pretty ugly imo and it doesn't cover all infinite custom http methods clients could be using.

Importance

nice to have

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions