代码之家  ›  专栏  ›  技术社区  ›  Tadhg McDonald-Jensen

React error overlay-显示一个错误,然后抛出另一个错误以调用代码来处理

  •  0
  • Tadhg McDonald-Jensen  · 技术社区  · 7 年前

    我目前有一个react应用程序,其中有一些异步函数处理redux操作。所有这些操作都包含在本文档中 Act

    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');
                }
            }
        };
    }
    

    console.trace 这还不足以让我意识到出了我没有预料到的错误,或者是因为错误从未进入UI,或者

    我真正想做的是,当在这些操作中抛出意外错误,并且dev模式处于启用状态时,它将显示错误覆盖,如果这是一个浮动承诺,那么将显示错误覆盖

    reportRuntimeError 从react error overlay,但我显然没有正确导入它,因为它被记录为 undefined

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

    我试过了 npm install @types/react-error-overlay

    1 回复  |  直到 7 年前
        1
  •  0
  •   Tadhg McDonald-Jensen    7 年前

    在写我的问题一半的时候意识到React显示了承诺的覆盖,这些承诺抛出了一个从未处理过的错误,所以我只需要做出一个承诺,恰好抛出了我想显示的错误,而不在任何地方处理它:

    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);
    }