import {ApiErrors} from '@config/api';
import {trackCustomHumandError} from '@hooks/useGeneralError';
import {CHATS_ERROR} from '@modules/chats/constants';

/**
 * Handle request error and execute the corresponding callback. If the error is a network error, `onNetworkError` is executed
 * otherwise `onError` is executed. If the error is not a network error, it is tracked in Sentry.
 */
export const handleRequestError = ({
  error,
  onNetworkError,
  onError,
}: {
  error: unknown;
  onNetworkError?: () => void;
  onError?: () => void;
}) => {
  if ((error as Error).message === ApiErrors.NETWORK_ERROR) {
    return onNetworkError?.();
  }

  trackCustomHumandError(error, CHATS_ERROR);

  return onError?.();
};
