Extract error handling with toast message as hook (#825)

This commit is contained in:
Chenlei Hu
2024-09-14 11:25:08 +09:00
committed by GitHub
parent c98ea5ba01
commit ebdcd92977
4 changed files with 78 additions and 35 deletions

28
src/hooks/errorHooks.ts Normal file
View File

@@ -0,0 +1,28 @@
import { useToast } from 'primevue/usetoast'
import { useI18n } from 'vue-i18n'
export function useErrorHandling() {
const toast = useToast()
const { t } = useI18n()
const wrapWithErrorHandling =
(action: (...args: any[]) => any, errorHandler?: (error: any) => void) =>
(...args: any[]) => {
try {
return action(...args)
} catch (e) {
if (errorHandler) {
errorHandler(e)
} else {
toast.add({
severity: 'error',
summary: t('error'),
detail: e.message,
life: 3000
})
}
}
}
return { wrapWithErrorHandling }
}