Blog>
Snippets

Error Handling in Redux Middlewares after Upgrade

Exhibit a method to handle errors in middlewares after updating to Redux v5.0.0.
const customMiddleware = store => next => action => {
  try {
    // Pass the action to the next middleware in the chain
    return next(action);
  } catch (error) {
    console.error('Caught an exception!', error);
    // Handle the error or dispatch an error action
    // store.dispatch({ type: 'ERROR', error });
    // Or re-throw the error if you don't want to handle it here
    throw error;
  }
}
This is a custom middleware that catches any errors that occur in the process of dispatching an action. If an error is caught, it logs the error to the console and gives the developer an option to handle it by dispatching an error action, or re-throw it to be handled by another error-catching mechanism.
const errorHandlingMiddleware = store => next => action => {
  return next(action).catch(error => {
    console.error('Async error caught in middleware:', error);
    // You can dispatch an error action or whatever you find suitable for your needs
    // store.dispatch({ type: 'ASYNC_ERROR', error });
    // Returning is important here to maintain the middleware chain
    return error;
  });
}
This middleware is specifically for handling errors in async actions or thunks. After passing the action to the next middleware, it attaches a catch block to the returned promise. Any rejected promise or thrown error from later middleware or async action creators will be handled here. Remember that not all actions return a promise, so ensure you are only applying this logic to async actions.