0

I currently have a react app where there are some async functions dealing with redux actions. All these actions are wrapped in this Act function to ensure that any unexpected errors are logged and a more user friendly error is sent to the UI code which then displays it to the user.

export function Act<R>(
    callback: (dispatch: Dispatch, getState: () => ReduxState) => Promise<R>
): typeof callback {
    return async (dispatch, getState) => {
        try {
            // if the callback works fine, just return it's value
            return await callback(dispatch, getState);
        } catch (e) {
            if (e instanceof UserError) {
                // we are expecting the action to throw these, although should still be logged
                console.log(`async callback threw user error: ${e}`);
                // propogate to UI code.
                throw e;
            } else {
                // Some exception happened that wasn't expected, log a traceback of the error
                console.trace(`Error in Async Action: ${e}`);
// HERE IS WHERE I WANT TO IMPROVE ^
                // since the error thrown will likely be shown to the user just show a generic message
                throw new UserError('something went wrong');
            }
        }
    };
}

This is working fine although sometimes console.trace isn't enough for me to realize something went wrong that I wasn't expecting, either because the error never makes it's way to the UI or

What I would really like to do is when an unexpected error is thrown in these actions and dev mode is on it would show the error overlay that would be shown if this was a floating promise

I tried using reportRuntimeError from react-error-overlay but I obviously didn't import it correctly since it was logged as undefined:

import { reportRuntimeError } from 'react-error-overlay'; // didn't work and couldn't find type definitions for the module

I tried npm install @types/react-error-overlay which wasn't able to find type definitions for that module and I'm not clear on whether that is the right place to even be trying to do this.

Is there a way to show the error that was originally thrown and then return a different one to be handled by the UI code?

Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59

1 Answers1

0

Realized about half way through writing my question that React shows the overlay for Promises that throw an error that are never handled, so I just had to make a promise that happens to throw the error I want to show and not handle it anywhere:

else {
    // This gets logged as an Unhandled Promise Rejection
    // so React will show the overlay for it as well.
    void Promise.reject(e);
    throw new UserError(fallbackErrorMessage);
}
Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59