0

我目前有一个反应应用程序,其中有一些处理 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,要么

我真正想做的是,当在这些操作中引发意外错误并且开发模式处于打开状态时,它将显示错误覆盖,如果这是一个浮动承诺,则会显示该错误覆盖

我尝试使用reportRuntimeErrorfrom 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了无法找到该模块的类型定义,我不清楚这是否是尝试执行此操作的正确位置。

有没有办法显示最初抛出的错误,然后返回另一个由 UI 代码处理的错误?

4

1 回答 1

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);
}
于 2019-03-10T23:23:15.387 回答