redux 如何记录从Reducer内部抛出的错误

jxct1oxe  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(107)

我是Redux的新手,有点难以将错误消息记录到控制台。我正在使用React,Redux Toolkit和TypeScript。
下面是我写的一个reducer的例子:

// Reducer
const removeResourceReducer = (state: ResourceCounts, action: ResourceAction) => {
  const { id, amount } = action.payload;
  assertIsPositive(amount);
  const has = state[id] ?? 0;
  if (amount > has) {
    throw new Error(`Trying to take ${amount} ${id} from global resources only containing ${has}`);
  }
  state[id] = has - amount;
  if (state[id] === 0) {
    delete state[id];
  }
  return state;
}

// Assertion functions
export const assert = (condition: any, msg: string): asserts condition => {
  if (!condition) {
    throw new Error(`Assertion Error: ${msg}`);
  }
}

export const assertIsPositive = (num: number) => {
  return assert(num > 0, `Expected a positive number, but got ${num}`);
}

字符串
如您所见,如果我传入的数量小于1或大于可用资源的数量,则会抛出错误。我希望将此错误记录到控制台,以便在devtools中检查它,但当我传递无效数字时,没有任何记录。为了实现这一点,我尝试添加一个自定义中间件,将next(action) Package 在try / catch块中,其中catch调用console.error(err),并且我还尝试将根组件渲染器 Package 在try / catch中以获得相同的结果-记录应用程序中的任何未处理错误。
谷歌搜索到目前为止还没有帮助我,所以有人能给予我一些想法吗?我假设Redux或Redux Toolkit中的某些东西正在捕获错误,但我不知道它对信息做了什么。

wlwcrazw

wlwcrazw1#

React Redux文档提供了一些中间件示例,其中之一是“crash reporter”。

/**
 * Sends crash reports as state is updated and listeners are notified.
 */
const crashReporter = store => next => action => {
  try {
    return next(action)
  } catch (err) {
    console.error('Caught an exception!', err)
    Raven.captureException(err, {
      extra: {
        action,
        state: store.getState()
      }
    })
    throw err
  }
}

字符串
一个简单的实现可能类似于以下内容:

const errorLogger = store => next => action => {
  try {
    return next(action);
  } catch(error) {
    // log the error/send to analytics/crashlytics/etc
    throw error;
  }
};
configureStore({
  reducer: rootReducer,
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware().concat(
      errorLogger,
    ),
  preloadedState,
});

的数据

Demo


的数据

相关问题