Files
ComfyUI_frontend/src/composables/useErrorHandling.ts
2025-02-05 15:05:56 -05:00

49 lines
1.2 KiB
TypeScript

import { t } from '@/i18n'
import { useToastStore } from '@/stores/toastStore'
export function useErrorHandling() {
const toast = useToastStore()
const toastErrorHandler = (error: any) => {
toast.add({
severity: 'error',
summary: t('g.error'),
detail: error.message
})
}
const wrapWithErrorHandling =
<TArgs extends any[], TReturn>(
action: (...args: TArgs) => TReturn,
errorHandler?: (error: any) => void,
finallyHandler?: () => void
) =>
(...args: TArgs): TReturn | undefined => {
try {
return action(...args)
} catch (e) {
;(errorHandler ?? toastErrorHandler)(e)
} finally {
finallyHandler?.()
}
}
const wrapWithErrorHandlingAsync =
<TArgs extends any[], TReturn>(
action: (...args: TArgs) => Promise<TReturn> | TReturn,
errorHandler?: (error: any) => void,
finallyHandler?: () => void
) =>
async (...args: TArgs): Promise<TReturn | undefined> => {
try {
return await action(...args)
} catch (e) {
;(errorHandler ?? toastErrorHandler)(e)
} finally {
finallyHandler?.()
}
}
return { wrapWithErrorHandling, wrapWithErrorHandlingAsync }
}