Skip to content

Simplify error handling middleware #1

Open
@patrick-fs

Description

@patrick-fs

I've chosen to demonstrate how the crashReporter middleware would work if you are using the redux-thunk package from npm. However, you can simplify things and remove code if you write your own simple thunk handler middleware.

remove the redux-thunk middleware

import { createStore, applyMiddleware } from 'redux';
// import thunk from 'redux-thunk'; //bye-bye redux-thunk middleware
import recordAction from './recordAction';
import crashReporter from './crashReporter';
import rootReducer from '../reducers';

const store = createStore(
  rootReducer,
  undefined,
  applyMiddleware(recordAction, crashReporter)
);

export default store;

update crashReporter to handle the thunk

import { doError } from '../actions/error';

const crashReporter = ({ dispatch }) => next => action => {
  // we got a thunk
  if (typeof action === 'function') {
    try {
        return action(dispatch);
    } catch (e) {
        dispatch(doError(e));
    }
  }
  
  try {
      return next(action);
  } catch (e) {
     dispatch(doError(e));
  }
};

export default crashReporter;

Gone is the additional code to wrap the thunk so that we can catch the error in the redux-thunk middleware.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions