Handling errors

Learn how to implement error handling.

Our current example ignores error handling. To solve this problem, we need to extend our middleware to catch server errors and dispatch events when they happen:

axios.get(url)
  .then(({ data }) => dispatch(onSuccess(data)))
  .catch(error => dispatch(apiError(error)));

The dispatched action creator apiError(error) could be caught by a special reducer to display an error message or another middleware for more processing.

In more complex scenarios, we might need an API request to have a custom error handler. To support this, we can extend our API middleware to support not just the onSuccess parameter in the action creator but also an onFailure one:

const fetchUser = id => ({
  type: API,
  payload: {
    url: `/user/${id}`,
    onSuccess: setUserData,
    onFailure: raiseAlarm
  }
});

We can now extend our API middleware to dispatch the action.payload.onFailure() action creator every time we have a failed network request or receive an error from the server:

const { url, onSuccess, onFailure } = action.payload;

axios.get(url)
  .then(({ data }) => dispatch(onSuccess(data)))
  .catch(error => {
    dispatch(apiError(error));

    if (onFailure) {
      dispatch(onFailure(error));
    }
  });

Get hands-on with 1200+ tech skills courses.