Skip to content

Commit

Permalink
feat: add safe effect helper (#552)
Browse files Browse the repository at this point in the history
* feat: add safeEffect as a saga helper
  • Loading branch information
alexruzenhack authored Sep 12, 2024
1 parent 93d6c08 commit 57b782c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
20 changes: 20 additions & 0 deletions src/sagas/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -353,3 +353,23 @@ export function* retryHandler(retryAction, dismissAction) {

return retry != null;
}

/**
* A wrapper effect to catch unexpected error and provide a binding
* for the desired handling behavior.
*
* @param {Object} effect The targeted effect.
* @param {(error) => void} onError The error handling effect,
* which receives the error object as first argument.
*
* @returns An anonymous effect.
*/
export function safeEffect(effect, onError) {
return function* _safeEffect(payload) {
try {
yield call(effect, payload);
} catch (error) {
yield call(onError, error);
}
}
}
17 changes: 15 additions & 2 deletions src/sagas/nanoContract.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import {
import { logger } from '../logger';
import { NANO_CONTRACT_TX_HISTORY_SIZE } from '../constants';
import { consumeGenerator, getNanoContractFeatureToggle } from '../utils';
import { getRegisteredNanoContracts } from './helpers';
import { getRegisteredNanoContracts, safeEffect } from './helpers';
import { isWalletServiceEnabled } from './wallet';

const log = logger('nano-contract-saga');
Expand Down Expand Up @@ -158,6 +158,16 @@ export function* registerNanoContract({ payload }) {
// emit action NANOCONTRACT_REGISTER_SUCCESS with feedback to user
yield put(nanoContractRegisterSuccess({ entryKey: ncId, entryValue: nc, hasFeedback: true }));
}
/**
* Effect invoked by safeEffect if an unexpected error occurs.
*
* @param {Object} error The error captured.
*/
function* registerNanoContractOnError(error) {
log.error('Unexpected error while registering Nano Contract.', error);
yield put(nanoContractRegisterFailure(failureMessage.nanoContractFailure));
yield put(onExceptionCaptured(error, false));
}

/**
* @typedef {Object} RawNcTxHistory
Expand Down Expand Up @@ -440,7 +450,10 @@ export function* requestBlueprintInfo({ payload }) {
export function* saga() {
yield all([
debounce(500, [[types.START_WALLET_SUCCESS, types.NANOCONTRACT_INIT]], init),
takeEvery(types.NANOCONTRACT_REGISTER_REQUEST, registerNanoContract),
takeEvery(
types.NANOCONTRACT_REGISTER_REQUEST,
safeEffect(registerNanoContract, registerNanoContractOnError)
),
takeEvery(types.NANOCONTRACT_HISTORY_REQUEST, requestHistoryNanoContract),
takeEvery(types.NANOCONTRACT_UNREGISTER_REQUEST, unregisterNanoContract),
takeEvery(types.NANOCONTRACT_ADDRESS_CHANGE_REQUEST, requestNanoContractAddressChange),
Expand Down

0 comments on commit 57b782c

Please sign in to comment.