Skip to content

Set headers for expected error (throw error(..))  #10300

@tiptenbrink

Description

@tiptenbrink

Describe the problem

Right now, when throwing an "expected" (expected as in described in the docs) error using throw error(...) on the server, you can only modify the body. If, for example, we are doing a broad check in the handle function in hooks.server.ts, this might originate from both an API request or from a page load. In the case of the API request, we might want to include some headers, e.g. when required by a spec (for example, technically, responding 401 Unauthorized requires setting WWW-Authenticate headers).

Of course, we could craft the response ourselves. However, if we also want to do this check when it comes from a page load, it would require quite a lot of work to ensure the +error.svelte is still rendered. The error helper exists to make it easy to send a status code for a broad range of cases, why not also let you include a header?

Describe the proposed solution

Add an additional parameter to the error helper, e.g. headers, where you pass in a Headers object. This would then add these headers to the response.

Alternatives considered

As mentioned above, it's possible to make your own custom response. That does mean you can no longer use the error helper, which is very useful (as in the case of for instance, an API request that only accepts JSON it will send a JSON response, while in the case of a page load it will send the nearest +error.svelte page) and also makes it easy to see for others when reading code that this is where an error is thrown.

Importance

would make my life easier

Additional Information

This is very closely related to #9188, although in that case it concerns unexpected errors, which are handled through the handleError. Somewhat related is also #8393, because even if this is solved, the error helper isn't as useful in hooks.server.ts as this only renders the static error.html page. If that issue is solved, this also becomes more useful.

I can make a PR for this if the Svelte team accepts that this is useful.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions