Blog>
Snippets

Integrating Redux-Saga with External Error Tracking Services

Provide an example of how to send caught saga errors to an external error tracking service, such as Sentry or LogRocket.
import { call, put } from 'redux-saga/effects';
import { showError } from '../actions/errorActions';
import LogRocket from 'logrocket';
Imports 'call' and 'put' from redux-saga/effects for handling side effects, the action creator 'showError' for dispatching an error action, and LogRocket for sending errors to the LogRocket service.
function* errorHandler(error) {
  // Log error to the console
  console.error(error);
  // Dispatch an action to update state with the error
  yield put(showError(error.message));
  // Send error to LogRocket
  LogRocket.error(error);
}
Defines a generator function for handling errors. It logs the error to the console, dispatches an action to update the application state with the error message, and sends the error to LogRocket.
function* fetchUserDataSaga(action) {
  try {
    // Attempt to fetch user data
    const userData = yield call(fetchUserData, action.payload);
    // More actions can be put here if fetch is successful
  } catch (error) {
    // If an error occurs, handle it using the errorHandler saga
    yield call(errorHandler, error);
  }
}
Defines a saga for fetching user data. It attempts to fetch user data and if an error occurs, it catches the error and handles it using the previously defined errorHandler saga.