Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: catch exceptions in fallback functions #510

Merged
merged 1 commit into from
Dec 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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