Skip to content

Instantly share code, notes, and snippets.

@melvinkcx
Last active January 21, 2022 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melvinkcx/7a02480a8f57327756ff27d29219e4a4 to your computer and use it in GitHub Desktop.
Save melvinkcx/7a02480a8f57327756ff27d29219e4a4 to your computer and use it in GitHub Desktop.
Handling Errors Globally In React

Handling Global Errors In React

My Approach: React Context with a custom useError hook

Even though React provides Error Boundaries API, it is not a good candidate, nor is relevant for handling GraphQL query errors.

useError custom hook

import { useState, useCallback } from 'react';

export const useError = () => {
    /**
     * Reminder:
     * - multiple calls to useError() create multiple isolated states
     * 
     * Solution:
     * - use `useContext`, and pass an instance of useError via the Context object
     */
    const [errorCode, setErrorCode] = useState('');
    const [errorMessage, setErrorMessage] = useState('');

    const setError = useCallback(
        (err: any) => {
            if (!err) return;
            const { code, message } = err;
            setErrorCode(code);
            setErrorMessage(message);
        },
        [setErrorCode, setErrorMessage],
    );

    return { errorCode, errorMessage, setError };
};

Custom Context

export App = () => {
  const {errorCode, errorMessage, setError} = useError();
  
  return (
    <MyCustomContext.Provider 
      value={{ errorCode, errorMessage, setError }}
    >
      <NotificationBar severity="error" errorMesage={errorMessage} errorCode={errorCode} />
      <... />
    </MyCustomContext.Provider>
  );
}
@rohailtaha
Copy link

Nice one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment