Blog>
Snippets

Error Handling Middleware in Redux Actions

Illustrate the creation of middleware that catches and processes errors from failed actions or asynchronous operations within a Redux application.
// Define error handling middleware
const errorHandlingMiddleware = ({ dispatch, getState }) => next => action => {
  try {
    // Pass action to the next middleware or reducer
    return next(action);
  } catch (error) {
    // Handle error here. For example, dispatching an error action
    dispatch({ type: 'ERROR_OCCURRED', error });
    return error;
  }
};

// Apply middleware to the Redux store
const { createStore, applyMiddleware } = Redux;
const rootReducer = (state = {}, action) => state;
const store = createStore(
  rootReducer,
  applyMiddleware(errorHandlingMiddleware)
);
This snippet defines a Redux middleware called 'errorHandlingMiddleware'. When an error is thrown while dispatching an action, the middleware catches it, dispatches an 'ERROR_OCCURRED' action with the error, and returns the error. It also demonstrates how to apply this middleware to a Redux store.