反应错误覆盖-显示一个错误然后抛出另一个错误以调用代码来处理

时间:2019-03-10 23:23:15

标签: reactjs error-handling react-redux react-devtools

我目前有一个react应用,其中有一些异步功能处理redux动作。所有这些操作都包装在此Act函数中,以确保记录任何意外错误,并将更加用户友好的错误发送到UI代码,然后将其显示给用户。

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或

我真正想做的是,在这些操作中引发意外错误并且在开发人员模式下时,它将显示错误叠加,如果这是一个浮动承诺,则会显示该错误覆盖

我尝试从react-error-overlay使用reportRuntimeError,但是由于它被记录为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,它找不到该模块的类型定义,而且我不清楚这是否是尝试执行此操作的正确位置。

是否可以显示最初引发的错误,然后返回由UI代码处理的错误?

1 个答案:

答案 0 :(得分:0)

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

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