Search code examples
javascripthttp-redirectpromisesveltesveltekit

How to call error() from within an async function in Svelte?


When using error() from inside an async function, the script crashes with this error.

Using import { error } from '@sveltejs/kit';

How can I call error() from within an async function in Svelte?

node:internal/process/promises:289
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "#<Redirect>".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

Node.js v20.11.0

Code Minimum Sample src/routes/+page.svelte (loading base URL)

<script lang="ts">
    import { error } from '@sveltejs/kit';

    const tst = async() => error( 400, 'My error message' );

    tst();
</script>

Case 2 This code produces a smilar error (uncaught (in promise)) in the JS console

<script lang="ts">
    import { error } from '@sveltejs/kit';
    import { onMount } from 'svelte';

    onMount( async function() 
    {
        error( 400, 'My error message' );
    } ); 
</script>

Screenshot

enter image description here

Removing async from the function does solves this issue, but I would like to use async please.

And I also would like to avoid having to use try .. catch around every async function call.


Solution

  • error is meant for server functions like load and returns the HTTP response with the respective status. If you get the error from some server-side function, you probably forgot to await some function.

    You should generally not use/need error in client code.

    On the client I would opt to show errors within the given page or show something like an error notification rather than showing an entire error page (which can be unnecessarily disruptive).

    You could still show an error page by e.g. setting up a context in a layout and conditionally show an error component rather than the slot containing the page. The context could contain a callback that can be invoked by a page on error.