import { toast } from 'sonner'; import { AxiosError } from 'axios'; interface BackendErrorResponse { message?: string; status?: boolean; data?: unknown; } /** * Handles backend errors and displays appropriate toast messages. * * Expected error response format: * { * "message": "exception.login.failed", * "status": false, * "data": null * } * * If the response doesn't match this format, it will show the error message * from the exception instead. */ export const handleBackendError = (error: unknown): void => { // Check if it's an AxiosError if (error instanceof Error && 'isAxiosError' in error) { const axiosError = error as AxiosError; const response = axiosError.response; // Handle errors with response (non-2xx status codes) if (response) { const errorData = response.data; // Check if the response matches the expected format if (errorData && typeof errorData === 'object' && 'message' in errorData && 'status' in errorData) { // Use the message from the backend response const errorMessage = errorData.message || 'An error occurred'; toast.error(errorMessage); return; } // If the response doesn't match the expected format, // try to extract a message from the response data if (errorData && typeof errorData === 'object') { const errorObj = errorData as Record; const message = (typeof errorObj.message === 'string' ? errorObj.message : null) || (typeof errorObj.error === 'string' ? errorObj.error : null) || response.statusText || 'An error occurred'; toast.error(message); return; } } // Handle network errors (no response) - connection refused, timeout, etc. if (axiosError.code === 'ERR_NETWORK' || !response) { const networkErrorMessage = axiosError.message || 'Network error. Please check your connection and try again.'; toast.error(networkErrorMessage); return; } // Fallback for other AxiosError cases const errorMessage = axiosError.message || 'An error occurred'; toast.error(errorMessage); return; } // If it's not an axios error, show a generic message if (error instanceof Error) { toast.error(error.message || 'An error occurred'); return; } // Final fallback toast.error('An unexpected error occurred'); };