File size: 1,641 Bytes
9853396 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | import { useCallback } from 'react';
import { ZodError } from 'zod';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
export function useErrorHandler() {
const { t } = useTranslation();
const handleError = useCallback(
(error: unknown, context?: string) => {
let errorMessage = t('common.errors.unknownError');
if (error instanceof ZodError) {
// Schema validation error
const fieldErrors =
error.issues
?.map((err: any) => {
const path = err.path.join('.');
return `${path}: ${err.message}`;
})
.join(', ') || 'Validation failed';
errorMessage = t('common.errors.validationFailed', { details: fieldErrors });
toast.error(t('common.errors.validationError'), {
description: errorMessage,
duration: 5000,
});
} else if (error instanceof Error) {
errorMessage = error.message;
if (context) {
toast.error(t('common.errors.operationFailed', { operation: context }), {
description: errorMessage,
duration: 4000,
});
} else {
toast.error(errorMessage);
}
} else {
// Unknown error type
if (context) {
toast.error(t('common.errors.operationFailed', { operation: context }), {
description: errorMessage,
duration: 4000,
});
} else {
toast.error(errorMessage);
}
}
},
[t]
);
return { handleError };
}
|