Skip to content

Commit

Permalink
Added typed error (#10)
Browse files Browse the repository at this point in the history
* added typed error

* added test, changed Err name

* added common error type

* renamed Error

* implemented requested changes
  • Loading branch information
enrichman authored and YoshiyukiMineo committed Sep 25, 2017
1 parent 572391e commit 1501d51
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 18 deletions.
20 changes: 10 additions & 10 deletions gobreaker.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package gobreaker

import (
"errors"
"fmt"
"sync"
"time"
Expand All @@ -18,6 +19,13 @@ const (
StateOpen
)

var (
// ErrTooManyRequests is returned when the CB state is half open and the requests count is over the cb maxRequests
ErrTooManyRequests = errors.New("too many requests")
// ErrOpenState is returned when the CB state is open
ErrOpenState = errors.New("circuit breaker is open")
)

// String implements stringer interface.
func (s State) String() string {
switch s {
Expand Down Expand Up @@ -237,9 +245,9 @@ func (cb *CircuitBreaker) beforeRequest() (uint64, error) {
state, generation := cb.currentState(now)

if state == StateOpen {
return generation, cb.errorStateOpen()
return generation, ErrOpenState
} else if state == StateHalfOpen && cb.counts.Requests >= cb.maxRequests {
return generation, fmt.Errorf("too many requests")
return generation, ErrTooManyRequests
}

cb.counts.onRequest()
Expand Down Expand Up @@ -334,11 +342,3 @@ func (cb *CircuitBreaker) toNewGeneration(now time.Time) {
cb.expiry = zero
}
}

func (cb *CircuitBreaker) errorStateOpen() error {
if cb.name == "" {
return fmt.Errorf("circuit breaker is open")
}

return fmt.Errorf("circuit breaker '%s' is open", cb.name)
}
8 changes: 0 additions & 8 deletions gobreaker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,11 +346,3 @@ func TestCircuitBreakerInParallel(t *testing.T) {
}
assert.Equal(t, Counts{total, total, 0, total, 0}, customCB.counts)
}

func TestErrorStateOpen(t *testing.T) {
err := defaultCB.errorStateOpen()
assert.Equal(t, "circuit breaker is open", err.Error())

err = customCB.errorStateOpen()
assert.Equal(t, "circuit breaker 'cb' is open", err.Error())
}

0 comments on commit 1501d51

Please sign in to comment.