-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Description
Describe the problem
We have a monorepo with a custom Exception class. We have shared module code between our svelte app and other apps.
We may have a shared function like getUser, and if the user isn't found we throw MyException.NotFound(...). This allows us to add custom metadata to our errors, and is quite a common pattern form my experience.
However, currently we cannot set the status code from within hooks.server.ts when we use these exceptions. As you can see below in handleError, there is no way to set the status directly, just the message.
import { HttpCode, MyException } from "$lib/error";
import type { Handle, HandleServerError } from "@sveltejs/kit";
import { error as svelteKitError } from "@sveltejs/kit";
export const handle: Handle = async ({ event, resolve }) => {
if (event.url.pathname.startsWith("/custom")) {
return new Response("custom response");
}
try {
const response = await resolve(event);
return response;
} catch (error) {
// THIS WILL NEVER BE REACHED BECAUSE resolve WILL NEVER THROW AN ERROR
// This is correct behavior IMO, but just wanted to include
if (error instanceof MyException) {
svelteKitError(error.httpCode ?? HttpCode.InternalServerError, {
message: error.externalMessage ?? "Internal Server Error",
});
}
throw error;
}
};
export const handleError: HandleServerError = ({ error, event }) => {
if (error instanceof MyException) {
// THIS WILL BE REACHED, however we can only set a new message here, not the status code
return {
message: error.externalMessage ?? "Internal Server Error",
status: error.httpCode ?? HttpCode.InternalServerError, // THIS WILL BE IGNORED
};
}
throw error;
};
Demo Repo
https://github.com/Ryanjso/svelte-error-demo/blob/main/src/hooks.server.ts
See this Discord thread for more details
https://discord.com/channels/457912077277855764/1412544875412324392
Describe the proposed solution
Let us overwrite the status code from handleError middleware
Alternatives considered
No response
Importance
i cannot use SvelteKit without it
Additional Information
No response