 
                        我对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或大于可用资源的数量,就会抛出一个错误。我希望将这个错误记录到控制台中,以便在开发工具中进行检查,但是当我传入一个无效的数字时,没有任何日志记录。为了实现这一点,我尝试添加了一个自定义中间件,将next(action)包装在try / catch块中,catch块调用console.error(err),我还尝试将我的根组件渲染器包装在try / catch中,以获得相同的结果-记录应用程序中的任何未处理错误。
谷歌搜索没有帮助我,所以有人能给我一些想法吗?我猜Redux或Redux Toolkit中的某些东西捕获了错误,但我不知道它对信息做了什么。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
React Redux文档提供了一些中间件示例,其中之一是"crash reporter"。
一个简单的实现可以像下面这样:
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