Line data Source code
1 : import { t } from '@/i18n'
2 : import { useToast } from '@/components/ui/toast/toastStore'
3 :
4 : /**
5 : * Strategy for recovering from specific error conditions.
6 : * Allows operations to be retried after resolving the error condition.
7 : *
8 : * @template TArgs - The argument types of the operation to be retried
9 : * @template TReturn - The return type of the operation
10 : *
11 : * @example
12 : * ```typescript
13 : * const networkRecovery: ErrorRecoveryStrategy = {
14 : * shouldHandle: (error) => error instanceof NetworkError,
15 : * recover: async (error, retry) => {
16 : * await waitForNetwork()
17 : * await retry()
18 : * }
19 : * }
20 : * ```
21 : */
22 : export interface ErrorRecoveryStrategy<
23 : TArgs extends unknown[] = unknown[],
24 : TReturn = unknown
25 : > {
26 : /**
27 : * Determines if this strategy should handle the given error.
28 : * @param error - The error to check
29 : * @returns true if this strategy can handle the error
30 : */
31 : shouldHandle: (error: unknown) => boolean
32 :
33 : /**
34 : * Attempts to recover from the error and retry the operation.
35 : * This function is responsible for:
36 : * 1. Resolving the error condition (e.g., reauthentication, network reconnect)
37 : * 2. Calling retry() to re-execute the original operation
38 : * 3. Handling the retry result (success or failure)
39 : *
40 : * @param error - The error that occurred
41 : * @param retry - Function to retry the original operation
42 : * @param args - Original arguments passed to the operation
43 : * @returns Promise that resolves when recovery completes (whether successful or not)
44 : */
45 : recover: (
46 : error: unknown,
47 : retry: (...args: TArgs) => Promise<TReturn> | TReturn,
48 : args: TArgs
49 : ) => Promise<void>
50 : }
51 :
52 2688959 : export function useErrorHandling() {
53 2688959 : const toast = useToast()
54 2688959 : const toastErrorHandler = (error: unknown) => {
55 : const isNetworkError =
56 : error instanceof TypeError &&
57 : /failed to fetch|networkerror|load failed/i.test(error.message)
58 29 : const message = isNetworkError
59 : ? t('g.disconnectedFromBackend')
60 : : error instanceof Error
61 : ? error.message
62 : : t('g.unknownError')
63 29 : toast.error(t('g.error'), { description: message })
64 29 : console.error(error)
65 : }
66 :
67 2688959 : const wrapWithErrorHandling =
68 : <TArgs extends unknown[], TReturn>(
69 : action: (...args: TArgs) => TReturn,
70 : errorHandler?: (error: unknown) => void,
71 : finallyHandler?: () => void
72 : ) =>
73 : (...args: TArgs): TReturn | undefined => {
74 30558 : try {
75 30558 : return action(...args)
76 : } catch (e) {
77 0 : ;(errorHandler ?? toastErrorHandler)(e)
78 : } finally {
79 30558 : finallyHandler?.()
80 : }
81 : }
82 :
83 2688959 : const wrapWithErrorHandlingAsync =
84 : <TArgs extends unknown[], TReturn>(
85 : action: (...args: TArgs) => Promise<TReturn> | TReturn,
86 : errorHandler?: (error: unknown) => void,
87 : finallyHandler?: () => void,
88 : recoveryStrategies: ErrorRecoveryStrategy<TArgs, TReturn>[] = []
89 : ) =>
90 : async (...args: TArgs): Promise<TReturn | undefined> => {
91 9655 : try {
92 9655 : return await action(...args)
93 : } catch (e) {
94 1 : for (const strategy of recoveryStrategies) {
95 1 : if (strategy.shouldHandle(e)) {
96 0 : try {
97 0 : await strategy.recover(e, action, args)
98 0 : return
99 : } catch (recoveryError) {
100 0 : console.error('Recovery strategy failed:', recoveryError)
101 : }
102 : }
103 : }
104 :
105 1 : ;(errorHandler ?? toastErrorHandler)(e)
106 : } finally {
107 9421 : finallyHandler?.()
108 : }
109 : }
110 :
111 2688959 : return {
112 : wrapWithErrorHandling,
113 : wrapWithErrorHandlingAsync,
114 : toastErrorHandler
115 : }
116 : }
|