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
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.
await
ing something you could, for example, throw an error and look for it in acatch
block and then return a redirect based on that.async function
insideasync
insideasync
insideasync
, through multiple files. Do I need tothrow
andtry - catch
that for every hierarchical call? (e.g.try { await x(); } catch( e ) { redirect( .. ); async x() { try { await y(); } catch( e ) { throw new Error( 'error' ) }
etc?my_http_request
called? If you are on the page you are supposed to usegoto
, notredirect
.+page-server.ts