116

I have one reducer for Clients, one other for AppToolbar and some others...

Now lets say that I created a fetch action to delete client, and if it fails I have code in the Clients reducer which should do some stuff, but also I want to display some global error in AppToolbar.

But the Clients and the AppToolbar reducers do not share the same part of the state and I cannot create a new action in the reducer.

So how am I suppose to show global error? Thanks

UPDATE 1:

I forget to mention that I use este devstack

UPDATE 2: I marked Eric's answer as correct, but I have to say that solution which I am using in este is more like combination of Eric and Dan's answer... You just have to find what fits you the best in your code...

3
  • 3
    You are getting close votes, and it's probably because you're not providing a whole lot of example code. Your question and the answers you get will be more helpful to other people if the problem is outlined more clearly.
    – acjay
    Dec 22, 2015 at 3:42
  • I have to agree w/ @acjay that this question is lacking in context. I've answered below (with code examples) with a general solution, but your question could use some refinement. It seems like you may have a few separate issues. 1) Handling async actions/errors. 2) Splitting up state appropriately in your redux state tree. 3) Getting your components the data that they need.
    – Erik Aybar
    Dec 22, 2015 at 18:54
  • @ErikTheDeveloper thanks, your answer looks great. But you are right, I forget to mention the context. I edited my question, I am using este devstack and it looks like your answer is not applicable there as it is... Dec 26, 2015 at 13:51

6 Answers 6

128

If you want to have the concept of "global errors", you can create an errors reducer, which can listen for addError, removeError, etc... actions. Then, you can hook into your Redux state tree at state.errors and display them wherever appropriate.

There are a number of ways you could approach this, but the general idea is that global errors/messages would merit their own reducer to live completely separate from <Clients />/<AppToolbar />. Of course if either of these components needs access to errors you could pass errors down to them as a prop wherever needed.

Update: Code Example

Here is one example of what it might look like if you were to pass the "global errors" errors into your top level <App /> and conditionally render it (if there are errors present). Using react-redux's connect to hook up your <App /> component to some data.

// App.js
// Display "global errors" when they are present
function App({errors}) {
  return (
    <div>
      {errors && 
        <UserErrors errors={errors} />
      }
      <AppToolbar />
      <Clients />
    </div>
  )
}

// Hook up App to be a container (react-redux)
export default connect(
  state => ({
    errors: state.errors,
  })
)(App);

And as far as the action creator is concerned, it would dispatch (redux-thunk) success failure according to the response

export function fetchSomeResources() {
  return dispatch => {
    // Async action is starting...
    dispatch({type: FETCH_RESOURCES});

    someHttpClient.get('/resources')

      // Async action succeeded...
      .then(res => {
        dispatch({type: FETCH_RESOURCES_SUCCESS, data: res.body});
      })

      // Async action failed...
      .catch(err => {
        // Dispatch specific "some resources failed" if needed...
        dispatch({type: FETCH_RESOURCES_FAIL});

        // Dispatch the generic "global errors" action
        // This is what makes its way into state.errors
        dispatch({type: ADD_ERROR, error: err});
      });
  };
}

While your reducer could simply manage an array of errors, adding/removing entries appropriately.

function errors(state = [], action) {
  switch (action.type) {

    case ADD_ERROR:
      return state.concat([action.error]);

    case REMOVE_ERROR:
      return state.filter((error, i) => i !== action.index);

    default:
      return state;
  }
}
4
  • 2
    Erik, I have something similar to what you have suggested here but surprisingly I never manage to get catch functions called if someHttpClient.get('/resources') or fetch('/resources') which I use in my code return 500 Server Error. Do you have any thoughts off the top of your head where I might be making mistake? Essentially, what I do is fetch does sent a request which ends up with my routes wherein I call a method on my mongoose model for doing something very simple, like adding a text or removing a text from DB. Aug 14, 2016 at 0:16
  • 4
    Hey, I came here from a Google search - just wanted to thank you for a great example.. I've been struggling with the same issues, and this is brilliant. Of course the solution is to integrate errors into the store. Why didn't I think of that... cheers
    – Spock
    Sep 9, 2016 at 10:59
  • 2
    How would one execute a function when an error occurs? e.g. I need to show a toast/alert in the UI, not render an Alert component by updating the props of the parent component Jan 29, 2019 at 10:51
  • How can we add the ADD_ERROR to a reducer error case when using createSlice using redux-toolkit.
    – technazi
    Nov 5, 2020 at 21:16
116

Erik’s answer is correct but I would like to add that you don’t have to fire separate actions for adding errors. An alternative approach is to have a reducer that handles any action with an error field. This is a matter of personal choice and convention.

For example, from Redux real-world example that has error handling:

// Updates error message to notify about the failed fetches.
function errorMessage(state = null, action) {
  const { type, error } = action

  if (type === ActionTypes.RESET_ERROR_MESSAGE) {
    return null
  } else if (error) {
    return error
  }

  return state
}
6
  • Does it mean on every success request we should pass RESET_ERROR_MESSAGE type to errorMessage reducer ? Jul 12, 2016 at 5:17
  • 2
    @DimitriMikadze no it does not. This function is just reducer for errors state. If you pass RESET_ERROR_MESSAGE it will clear all the error messages. If you do not pass and there is no error field, it just return unchanged state, so if there was some errors from previous actions, they still will be there after success action.... Aug 9, 2016 at 9:51
  • I prefer this approach because it allows for a more natural inline response as the consumer attaches the error to the action payload. Thanks Dan! Oct 23, 2017 at 11:29
  • 1
    I can't quite get my head around how this works. Aside from the real-world example, do you have any isolated and documents/videos explaining this? It's a pretty core requirement of most projects, and I've found little easy to understand documentation on the subject. Thanks. Oct 31, 2017 at 15:59
  • 7
    @MattSaunders While trying to understand it I came across a Redux course by Dan himself (the answerer, who's actually the creator of Redux), with a section on Displaying Error Messages which together with these answers and the real-world example drove it home for me. Good luck. Nov 16, 2017 at 14:40
2

The approach I'm currently taking for a few specific errors (user input validation) is to have my sub-reducers throw an exception, catch it in my root reducer, and attach it to the action object. Then I have a redux-saga that inspects action objects for an error and update the state tree with error data in that case.

So:

function rootReducer(state, action) {
  try {
    // sub-reducer(s)
    state = someOtherReducer(state,action);
  } catch (e) {
    action.error = e;
  }
  return state;
}

// and then in the saga, registered to take every action:
function *errorHandler(action) {
  if (action.error) {
     yield put(errorActionCreator(error));
  }
}

And then adding the error to the state tree is as Erik describes.

I use it pretty sparingly, but it keeps me from having to duplicate logic which legitimately belongs in the reducer (so it can protect itself from an invalid state).

1

write custom Middleware to handle all the api related error. In this case your code will be more cleaner.

   failure/ error actin type ACTION_ERROR

   export default  (state) => (next) => (action) => {

      if(ACTION_ERROR.contains('_ERROR')){

       // fire error action
        store.dispatch(serviceError());

       }
}
3
  • 2
    Also makes it harder to debug IMHO
    – chrisjlee
    May 29, 2018 at 1:11
  • 3
    You don't need middleware for this, you can write the exact same if in a reducer
    – Juan Campa
    Jun 9, 2018 at 15:42
  • If there are more than 50 api's then you need to write in everyplace. Instead you can write custom middleware to check the error.
    – Shrawan
    Sep 27, 2019 at 9:50
1

what I do is I centralize all error handling in the effect on a per effect basis

/**
 * central error handling
 */
@Effect({dispatch: false})
httpErrors$: Observable<any> = this.actions$
    .ofType(
        EHitCountsActions.HitCountsError
    ).map(payload => payload)
    .switchMap(error => {
        return of(confirm(`There was an error accessing the server: ${error}`));
    });
-8

You can use axios HTTP client. It already has implemented Interceptors feature. You can intercept requests or responses before they are handled by then or catch.

https://github.com/mzabriskie/axios#interceptors

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

2
  • Yes but you are not dispatching anything to redux? May 18, 2017 at 11:16
  • This approach is not bad. Usually store in redux is a singleton and you can import store in axios interceptors file and use store.dispatch() to trigger any actions. This is unitary approach to handle all api errors in the system in 1 place
    – Wedmich
    Jun 29, 2020 at 10:34

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.