Search code examples
error-handlingsveltesveltekitprogressive-enhancement

throw error() doesn't redirect to error page in Sveltekit


So i have a form that uses use:enhance and i check if there is an error in the result to throw an error.

But whn I throw the error it shows in the console, but it doesn't redirect to my +error.svelte page

Here's my use:enhance code :

use:enhance={() => {
        //disabling form and button
        formDisabled = true;

        return async ({ result }) => {
          //@ts-ignore
          if (result.type === "success" && result.data.success === true) {
            //reactivating the form
            formDisabled = false;
          } else {
            throw error(500, {
              message: "Internal Server Error",
            });
          }
        };
      }}

I also tried to put the throw error in the onMount() to see if it would redirect me if it is at the start but it still doesn't :/

I really have no idea because in the docs it says that throw error() should redirect and I never had a problem with it before


Solution

  • These errors only really work during SSR and in server code like the load function. The problem presumably is, that the code running on the client does not run in a context where all errors can be easily handled.

    enhance probably could implement the logic since it is provided by SvelteKit but from your observations it looks like that is not the case.

    There are various potential workarounds:

    • Throw errors earlier, on the server during the action
      • If a result handle function is returned by enhance, you need to use update or applyAction to handle errors (see docs)
    • Use validation error handling instead, which is the intended way of handling issues with form actions.
      • return a fail
      • use form property and conditionally show some error content directly
    • (Redirect to an error page using goto, this is not really recommended as the user will be stuck on the error page on refresh)

    Possibly not a good idea, but applyAction can also be used in non-action contexts, e.g.:

    onMount(() => {
        applyAction({ type: 'error', error: { message: 'Test error' } });
    });