Blog>
Snippets

Basic Error Logging in Redux-Saga

Show how to catch and log errors in a Redux-Saga worker saga using `try/catch` blocks.
import { call, put } from 'redux-saga/effects';
import { fetchUserDataFailed } from './actionCreators';
import { getUserData } from '../api';

function* fetchUserDataSaga(action) {
  try {
    const data = yield call(getUserData, action.payload);
    // Handle successful data fetching
  } catch (error) {
    console.error('Error fetching user data:', error);
    yield put(fetchUserDataFailed(error.message));
  }
}
This is a basic Redux-Saga worker saga that attempts to fetch user data using the getUserData API call. It uses a try/catch block to attempt fetching the data. If the call is successful, it proceeds to handle the retrieved data. If an error occurs during the fetch, the error is logged to the console, and an error action is dispatched using 'put' to update the application state accordingly.