Error Handling

Handling errors in side effects like AJAX calls is a common requirement of Epics. While there are several ways of doing this depending on your requirements, the most common way is to simply catch them inside your Epic and emit an action with the error information so you can display or log it.

This can be done with the catchError() RxJS operator:

import { ajax } from 'rxjs/ajax';

const fetchUserEpic = action$ => action$.pipe(
  mergeMap(action => ajax.getJSON(`/api/users/${action.payload}`).pipe(
    map(response => fetchUserFulfilled(response)),
    catchError(error => of({
      payload: error.xhr.response,
      error: true

Here we placed the catchError() inside our mergeMap(), but after our AJAX call; this is important because if we let the error reach the action$.pipe(), it will terminate it and no longer listen for new actions.

results matching ""

    No results matching ""