Skip to main content

Error Event Handler

Overview

This functional code handles ERROR events emitted by the onboarding SDK subscription. It extracts error messages from various error types and displays them to users via a snackbar notification system.

Code Breakdown

case 'ERROR':
  const error = event.data.payload.error;
  let message = '';

  if (error instanceof Error) {
    message = error.message;
  } else if (error instanceof AxiosError) {
    message = error.message;
  } else {
    message = (error as any)?.message;
  }

  enqueueSnackbar(message, {
    anchorOrigin: { vertical: 'top', horizontal: 'right' },
    variant: 'error',
  });

  setLoading(false);
  break;

Detailed Explanation

1. Event Subscribtion Handler

  • Executes when the onboarding SDK emits an ERROR event type.
  • Extracts the error object from the event payload.

2. Error Type Discrimination

  • Checks if the error is a standard JavaScript Error instance.
  • Extracts the message using error.message property.
  • This covers most native JavaScript errors.

Axios Error ((error instanceof AxiosError))

  • Specifically handles HTTP request errors from Axios library
  • Also uses error.message property.
  • Note: This check is somewhat redundant since AxiosError extends Error, but it’s explicit for clarity.

3. User Notification (enqueueSnackbar(...))

  • Uses the notistack library’s enqueueSnackbar function.
  • Displays the error message in a snackbar/toast notification.
  • Configuration:
    • anchorOrigin: { vertical: 'top', horizontal: 'right' } - Positions notification at top-right corner
    • variant: 'error' - Applies error styling (typically red color scheme).

4. Loading State Update (setLoading(false);)

  • Updates the component’s loading state to false.
  • This stops any loading indicators and makes the UI interactive again.
  • Ensures users aren’t stuck in a loading state after an error occurs.

Error Handling Robustness

  • Handles multiple error types gracefully.
  • However, the fallback case may result in an empty string if the error object lacks a message property.

User Experience

  • Errors are displayed non-intrusively via snackbar notifications.
  • Loading state is properly cleared to prevent UI lockup.
  • Error messages are user-facing, so they should be clear and actionable.

Dependencies

  • notistack: Provides enqueueSnackbar function for toast notifications.
  • axios : Provides AxiosError type for HTTP error handling.
  • React State: Uses setLoading state setter.