From dfdbd30f5be4c0063837186062f7dadefb3f90d4 Mon Sep 17 00:00:00 2001 From: Corentin Thomasset Date: Wed, 1 Nov 2023 10:53:05 +0100 Subject: [PATCH] refactor(composable): mutualized computedCatch --- src/composable/computed/catchedComputed.ts | 22 ++++++++++++++++++++++ src/tools/encryption/encryption.vue | 17 +++++------------ 2 files changed, 27 insertions(+), 12 deletions(-) create mode 100644 src/composable/computed/catchedComputed.ts diff --git a/src/composable/computed/catchedComputed.ts b/src/composable/computed/catchedComputed.ts new file mode 100644 index 00000000..fd00a128 --- /dev/null +++ b/src/composable/computed/catchedComputed.ts @@ -0,0 +1,22 @@ +import { type Ref, ref, watchEffect } from 'vue'; + +export { computedCatch }; + +function computedCatch(getter: () => T, { defaultValue }: { defaultValue: D; defaultErrorMessage?: string }): [Ref, Ref]; +function computedCatch(getter: () => T, { defaultValue, defaultErrorMessage = 'Unknown error' }: { defaultValue?: D; defaultErrorMessage?: string } = {}) { + const error = ref(); + const value = ref(); + + watchEffect(() => { + try { + error.value = undefined; + value.value = getter(); + } + catch (err) { + error.value = err instanceof Error ? err.message : err?.toString() ?? defaultErrorMessage; + value.value = defaultValue; + } + }); + + return [value, error] as const; +} diff --git a/src/tools/encryption/encryption.vue b/src/tools/encryption/encryption.vue index f4ebf380..2ad47b51 100644 --- a/src/tools/encryption/encryption.vue +++ b/src/tools/encryption/encryption.vue @@ -1,5 +1,6 @@ @@ -72,7 +65,7 @@ watchEffect(() => { /> - + {{ decryptError }}