aboutsummaryrefslogtreecommitdiff
path: root/src/composable/computed/catchedComputed.ts
blob: fd00a128f76780d24c36e8d34f965f5e1a5f00f5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { type Ref, ref, watchEffect } from 'vue';

export { computedCatch };

function computedCatch<T, D>(getter: () => T, { defaultValue }: { defaultValue: D; defaultErrorMessage?: string }): [Ref<T | D>, Ref<string | undefined>];
function computedCatch<T, D>(getter: () => T, { defaultValue, defaultErrorMessage = 'Unknown error' }: { defaultValue?: D; defaultErrorMessage?: string } = {}) {
  const error = ref<string | undefined>();
  const value = ref<T | D | undefined>();

  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;
}