Blog>
Snippets

Error Reporting Middleware

Showcase a middleware that catches exceptions during the dispatch process and reports them to an error tracking service while allowing the user to continue their workflow.
const createErrorReportingMiddleware = (errorReporter) => store => next => action => {
  try {
    // Pass action to the next middleware or reducer
    return next(action);
  } catch (error) {
    // Report caught exceptions to an error tracking service
    errorReporter.captureException(error);

    // Optionally enrich error information (action type, state, etc.)
    errorReporter.setExtra('action', action);
    errorReporter.setExtra('state', store.getState());

    // Throw error to console if needed (remove in production)
    console.error('Middleware error:', error);

    throw error; // re-throw the error if necessary
  }
};
This middleware captures any exceptions thrown during the dispatch process and reports them to an error tracking service defined by 'errorReporter'. The 'captureException' method is used to send the error to the service, and additional information about the action and state can be attached using 'setExtra'. Errors are also logged to the console for easier debugging during development.
const errorReporter = {
  captureException: (error) => console.log('Error reported:', error),
  setExtra: (key, info) => console.log(`Extra info - ${key}:`, info)
};

// Create the middleware with the custom errorReporter
const errorReportingMiddleware = createErrorReportingMiddleware(errorReporter);
This is an example of an 'errorReporter' object with 'captureException' and 'setExtra' methods that log errors and extra info to the console. In production, this should interface with a real error tracking service like Sentry. The 'errorReportingMiddleware' is created by passing this 'errorReporter' to the 'createErrorReportingMiddleware' function.
import { applyMiddleware, createStore } from 'redux';
import rootReducer from './reducers';

// Create the store with the error reporting middleware
const store = createStore(
  rootReducer,
  applyMiddleware(
    errorReportingMiddleware
    // ... other middlewares
  )
);
The Redux store is created using 'createStore'. The 'errorReportingMiddleware' is applied to the store using 'applyMiddleware'. This setup integrates the custom error reporting into the Redux dispatch process, and it should be combined with other middlewares as necessary.