【问题标题】:How to handle Errors and Exceptions in Redux Reducers?如何处理 Redux Reducer 中的错误和异常?
【发布时间】:2019-07-15 20:48:41
【问题描述】:

我们目前正在我们的 React / Redux 应用程序中测试我们的错误处理。 (我已经读过https://github.com/reduxjs/redux/issues/1960)。在 React 中,我们实现了 ErrorBoundaries,这运行得很好:没有更多未处理异常的空白页面。

不,我们尝试在 Reducers 中抛出错误,我们看到它们以未触及的 redux 状态登录到控制台。

reducer 必须是纯的!

我绝对可以支持这一点。该功能应该是“简单的”,没有副作用并且经过良好测试。问题是:reducer 开发人员可以做出错误的假设(例如,关于 redux 状态下的哪些属性可以是未定义的)。该示例导致

[Error] Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'someVariableWithCanBeNullOrUndefined.someFunction')

可以说:至少没有白页。但是现在 App 的状态有点尴尬,因为动作都被调度和执行了,但没有正确地减少。这些错误很容易被监督。 有没有办法处理这些编程运行时错误?甚至可以将它们呈现在 React 的 ErrorBoundary 中?

一个错误的reducer函数的例子,它只导致一个日志条目:

reduceSomeState(state = new SomeState(), action: SomeAction) {
    throw new Error('some runtime error: e.g. a value in the state is undefined and accessed here');
}

【问题讨论】:

  • 你能分享代码/一些示例代码吗?

标签: redux


【解决方案1】:

据我所知,reducersconnect(mapStateToProps, mapDispatchToProps)(View) 都无法处理异常。

虽然解决方案是设置一个全局错误处理程序。可以是这样的:

import * as React from 'react';
import {render} from 'react-dom';
import {GlobalErrorView} from '../../globalError/GlobalErrorView';

window.onerror = (event: Event | string, source?: string, lineno?: number, colno?: number, error?: Error) => {

    render(
        (
            <GlobalErrorView
                error={error}
                okAction={() => window.location.reload()}
            />
        ),
        document.getElementById('app') as HTMLElement
    );
};

【讨论】:

    猜你喜欢
    • 2017-06-09
    • 1970-01-01
    • 2017-05-16
    • 2017-08-27
    • 2017-04-03
    • 2014-04-06
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    相关资源
    最近更新 更多