diff --git a/packages/core/asyncComputed/index.test.ts b/packages/core/asyncComputed/index.test.ts index 83e1284dd9e9..f5df8c8f49fb 100644 --- a/packages/core/asyncComputed/index.test.ts +++ b/packages/core/asyncComputed/index.test.ts @@ -35,6 +35,28 @@ describe('asyncComputed', () => { expect(data.value).toBe('data') }) + it('call onError when error is thrown', async() => { + let errorMessage + const func = jest.fn(() => Promise.reject(new Error('An Error Message'))) + + const data = asyncComputed(func, undefined, { + onError(e) { + if (e instanceof Error) + errorMessage = e.message + }, + }) + + expect(func).toBeCalledTimes(1) + + expect(data.value).toBeUndefined() + + await nextTick() + await nextTick() + + expect(data.value).toBeUndefined() + expect(errorMessage).toBe('An Error Message') + }) + it('is lazy if configured', async() => { const func = jest.fn(() => Promise.resolve('data')) diff --git a/packages/core/asyncComputed/index.ts b/packages/core/asyncComputed/index.ts index fafd3aa31fca..f8aacbf7cba5 100644 --- a/packages/core/asyncComputed/index.ts +++ b/packages/core/asyncComputed/index.ts @@ -1,4 +1,4 @@ -import { Fn } from '@vueuse/shared' +import { Fn, noop } from '@vueuse/shared' import { ref, isRef, computed, watchEffect, Ref } from 'vue-demi' /** @@ -8,15 +8,23 @@ import { ref, isRef, computed, watchEffect, Ref } from 'vue-demi' */ export type AsyncComputedOnCancel = (cancelCallback: Fn) => void -/** - * Additional options for asyncComputed - * - * @property lazy Should value be evaluated lazily - * @property evaluating Ref passed to receive the updated of async evaluation - */ -export type AsyncComputedOptions = { +export interface AsyncComputedOptions { + /** + * Should value be evaluated lazily + * + * @default false + */ lazy?: Boolean + + /** + * Ref passed to receive the updated of async evaluation + */ evaluating?: Ref + + /** + * Callback when error is caught. + */ + onError?: (e: unknown) => void } /** @@ -46,6 +54,7 @@ export function asyncComputed( const { lazy = false, evaluating = undefined, + onError = noop, } = options const started = ref(!lazy) @@ -82,6 +91,9 @@ export function asyncComputed( if (counterAtBeginning === counter) current.value = result } + catch (e) { + onError(e) + } finally { if (evaluating) evaluating.value = false