Skip to content

Commit

Permalink
fix: circuit should emit failure event on fallback
Browse files Browse the repository at this point in the history
Fixes: #28
  • Loading branch information
lance committed Mar 6, 2017
1 parent 5a727c8 commit f2594d8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
12 changes: 6 additions & 6 deletions lib/circuit.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,8 @@ class CircuitBreaker extends EventEmitter {
* @event CircuitBreaker#reject
*/
this.emit('reject', new Error('Breaker is open'));
return fallback(this, 'Breaker is open', args) ||
fail(this, 'Breaker is open', args);
const failure = fail(this, 'Breaker is open', args);
return fallback(this, 'Breaker is open', args) || failure;
}
this[PENDING_CLOSE] = this.halfOpen;

Expand Down Expand Up @@ -218,15 +218,16 @@ class CircuitBreaker extends EventEmitter {
})
.catch((error) => {
clearTimeout(timeout);
fail(this, error, args);
const fb = fallback(this, error, args);
if (fb) return resolve(fb);
fail(this, error, args);
reject(error);
else reject(error);
});
});
} catch (error) {
clearTimeout(timeout);
return fallback(this, error, args) || fail(this, error, args);
fail(this, error, args);
return fallback(this, error, args);
}
}
}
Expand Down Expand Up @@ -257,7 +258,6 @@ function fail (circuit, err, args) {
if (circuit[NUM_FAILURES] >= circuit.options.maxFailures) {
circuit.open();
}

return circuit.Promise.reject.apply(null, [err]);
}

Expand Down
16 changes: 15 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,19 @@ test('Returns self from fallback()', (t) => {
.catch(t.fail);
});

test('CircuitBreaker emits failure when falling back', (t) => {
t.plan(2);
const breaker = cb(passFail).fallback(() => 'fallback value');

breaker.on('failure', (err) => {
t.equals(err, 'Error: -1 is < 0', 'Unexpected error');
});

breaker.fire(-1).then((result) => {
t.equals('fallback value', result, 'fallback value is correct');
}).catch(t.fail);
});

test('CircuitBreaker status', (t) => {
t.plan(11);
const breaker = cb(passFail, { maxFailures: 1 });
Expand All @@ -226,12 +239,13 @@ test('CircuitBreaker status', (t) => {
breaker.fire(-20)
.then((result) => {
t.equal(result, 'Fallback called', 'fallback is invoked');
t.equal(breaker.status.failures, 1, 'status reports 1 failures');
t.equal(breaker.status.failures, 2, 'status reports 2 failures');
t.equal(breaker.status.fires, 5, 'status reports 5 fires');
t.equal(breaker.status.fallbacks, 1, 'status reports 1 fallback');
})
.catch(t.fail);
})
.catch(t.fail)
.then(t.end);
});
});
Expand Down

0 comments on commit f2594d8

Please sign in to comment.