从async
函数内部使用error()
时,脚本崩溃,并显示以下错误.
使用import { error } from '@sveltejs/kit';
如何在Svelte中从async
函数中调用error()
?
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 Code Minimum Sample Code Minimum Sample Src/routes/+page.svelte(基本加载URL)
<script lang="ts">
import { error } from '@sveltejs/kit';
const tst = async() => error( 400, 'My error message' );
tst();
</script>
Case 2此代码在JS控制台中产生一个相似错误(未捕获(In Promise))
<script lang="ts">
import { error } from '@sveltejs/kit';
import { onMount } from 'svelte';
onMount( async function()
{
error( 400, 'My error message' );
} );
</script>
Screenshot个
从函数中删除异步确实解决了这个问题,但我想使用异步.
我还希望避免在每个异步函数调用中使用try .. catch
.