Search code examples
javascriptreduxredux-thunkredux-toolkit

Redux toolkit thunk action generic error handler


I'm enjoying redux-toolkit, but I'm wondering if there is a way to add a generic error handler for any rejected thunk? Just like the browser has the unhandledrejection event you can listen to, I'd like to report any rejected promises to my error tracker.


Solution

  • It sounds like you want to run a side effect (sending a message to the server) every time a thunk is rejected. I would suggest looking at our new "listener middleware" for Redux Toolkit, which specifically lets you trigger additional logic when certain actions are dispatched.

    The listener middleware is currently a separate @rtk-incubator/action-listener-middleware package as we've been iterating on its API, but as of today the API is stable and we plan to officially release it as part of RTK 1.8 shortly. You can use it in that package today, and switch to importing it from RTK as soon as that release comes out.

    Here's what it might look like:

    // app/listenerMiddleware.js
    import { isRejected } from '@reduxjs/toolkit';
    import { createListenerMiddleware } from '@rtk-incubator/action-listener-middleware';
    
    const listenerMiddleware = createListenerMiddleware()
    
    listenerMiddleware.startListening({
      matcher: isRejected,
      effect: async (action, listenerApi) => {
        // send a message to the server here containing info from the action
      },
    })