Skip to content

Commit

Permalink
fix: ensure fallback event always fires
Browse files Browse the repository at this point in the history
  • Loading branch information
lance committed Oct 8, 2017
1 parent fbedb07 commit 27c3f8b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
14 changes: 6 additions & 8 deletions lib/circuit.js
Original file line number Diff line number Diff line change
Expand Up @@ -411,15 +411,13 @@ function handleError (error, circuit, timeout, args, latency, resolve, reject) {
function fallback (circuit, err, args) {
if (circuit[FALLBACK_FUNCTION]) {
const result = circuit[FALLBACK_FUNCTION].apply(circuit[FALLBACK_FUNCTION], args);
/**
* Emitted when the circuit breaker executes a fallback function
* @event CircuitBreaker#fallback
*/
circuit.emit('fallback', result, err);
if (result instanceof Promise) return result;
return new Promise((resolve, reject) => {
/**
* Emitted when the circuit breaker executes a fallback function
* @event CircuitBreaker#fallback
*/
circuit.emit('fallback', result, err);
resolve(result);
});
return Promise.resolve(result);
}
}

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

test('CircuitBreaker fallback event as a rejected promise', (t) => {
t.plan(1);
const options = {
errorThresholdPercentage: 1,
resetTimeout: 100
};
const input = -1;
const breaker = cb(passFail, options);

breaker.fallback(() => Promise.reject(new Error('nope')));
breaker.on('fallback', result => {
result
.then(t.fail)
.catch(e => t.equals('nope', e.message))
.then(t.end);
});

breaker.fire(input).then(t.fail).catch(_ => {});
});

test('CircuitBreaker fallback as a CircuitBreaker', (t) => {
t.plan(1);
const options = {
Expand Down

0 comments on commit 27c3f8b

Please sign in to comment.