Skip to content

Commit

Permalink
fix: catch exceptions in fallback functions (#510)
Browse files Browse the repository at this point in the history
When a fallback function is called and throws an exception, the circuit
breaker should catch the exception and return a rejected Promise.

See: #509

Signed-off-by: Lance Ball <[email protected]>
  • Loading branch information
lance authored Dec 7, 2020
1 parent 05a8876 commit 34f75a2
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
22 changes: 13 additions & 9 deletions lib/circuit.js
Original file line number Diff line number Diff line change
Expand Up @@ -661,17 +661,21 @@ function handleError (error, circuit, timeout, args, latency, resolve, reject) {

function fallback (circuit, err, args) {
if (circuit[FALLBACK_FUNCTION]) {
const result =
try {
const result =
circuit[FALLBACK_FUNCTION]
.apply(circuit[FALLBACK_FUNCTION], [...args, err]);
/**
* Emitted when the circuit breaker executes a fallback function
* @event CircuitBreaker#fallback
* @type {any} the return value of the fallback function
*/
circuit.emit('fallback', result, err);
if (result instanceof Promise) return result;
return Promise.resolve(result);
/**
* Emitted when the circuit breaker executes a fallback function
* @event CircuitBreaker#fallback
* @type {any} the return value of the fallback function
*/
circuit.emit('fallback', result, err);
if (result instanceof Promise) return result;
return Promise.resolve(result);
} catch (e) {
return Promise.reject(e);
}
}
}

Expand Down
16 changes: 16 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -776,6 +776,22 @@ test('CircuitBreaker fallback as a CircuitBreaker', t => {
.then(t.end);
});

test('CircuitBreaker fallback that throws returns a rejected Promise', t => {
t.plan(1);
const options = {
errorThresholdPercentage: 1,
resetTimeout: 100
};
const breaker = new CircuitBreaker(passFail, options);
breaker.fallback(_ => { throw new Error('Fallback failed'); });

breaker.fire(-1)
.then(_ => t.fail('CircuitBreaker fallback should return rejected promise'))
.catch(e => t.equals(e.message, 'Fallback failed'))
.then(_ => breaker.shutdown())
.then(t.end);
});

test('options.maxFailures should be deprecated', t => {
const options = { maxFailures: 1 };
const originalLog = console.error;
Expand Down

0 comments on commit 34f75a2

Please sign in to comment.