| 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) {
|
|
|
| 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 {
|
|
|
| if (context) {
|
| toast.error(t('common.errors.operationFailed', { operation: context }), {
|
| description: errorMessage,
|
| duration: 4000,
|
| });
|
| } else {
|
| toast.error(errorMessage);
|
| }
|
| }
|
| },
|
| [t]
|
| );
|
|
|
| return { handleError };
|
| }
|
|
|