Skip to content

Commit

Permalink
fix: ensure breaker.fire() returns rejected promise when fallback fails
Browse files Browse the repository at this point in the history
Prior to this change, the user was required to handle promise rejections
from a fallback function during the fallback event. Now, the user may
choose to handle the rejected promise in the event handler, or in the
promise returned from `breaker.fire()`.

Fixes: #100
  • Loading branch information
lance committed Oct 8, 2017
1 parent 10aa9b3 commit fbedb07
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 9 deletions.
3 changes: 2 additions & 1 deletion lib/circuit.js
Original file line number Diff line number Diff line change
Expand Up @@ -410,8 +410,9 @@ 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);
if (result instanceof Promise) return result;
return new Promise((resolve, reject) => {
const result = circuit[FALLBACK_FUNCTION].apply(circuit[FALLBACK_FUNCTION], args);
/**
* Emitted when the circuit breaker executes a fallback function
* @event CircuitBreaker#fallback
Expand Down
11 changes: 3 additions & 8 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -581,14 +581,9 @@ test('CircuitBreaker fallback as a rejected promise', (t) => {
const breaker = cb(passFail, options);
breaker.fallback(() => Promise.reject(new Error('nope')));

breaker.on('fallback', (resultPromise) => {
resultPromise
.then(t.fail)
.catch((e) => t.equals('nope', e.message))
.then(t.end);
});

breaker.fire(input).catch(() => {});
breaker.fire(input).then(t.fail).catch(e => {
t.equals('nope', e.message);
}).then(t.end);
});

test('CircuitBreaker fallback as a CircuitBreaker', (t) => {
Expand Down

0 comments on commit fbedb07

Please sign in to comment.