Skip to content

Commit

Permalink
js: make an APIError implement the interface
Browse files Browse the repository at this point in the history
Signed-off-by: Waldemar Quevedo <wally@nats.io>
  • Loading branch information
wallyqs committed Aug 22, 2022
1 parent 36b8662 commit 8fee091
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
12 changes: 7 additions & 5 deletions jsm.go
Expand Up @@ -166,6 +166,11 @@ func (e *APIError) Error() string {
return fmt.Sprintf("nats: API error %d: %s", e.ErrorCode, e.Description)
}

// APIError implements the JetStreamError interface.
func (e *APIError) APIError() *APIError {
return e
}

// Is matches against an APIError.
func (e *APIError) Is(err error) bool {
// Extract internal APIError to match against.
Expand Down Expand Up @@ -303,14 +308,11 @@ func (js *js) AccountInfo(opts ...JSOpt) (*AccountInfo, error) {
return nil, err
}
if info.Error != nil {
var err error
var err JetStreamError = info.Error

// Internally checks based on error code instead of description match.
if errors.Is(info.Error, ErrJetStreamNotEnabledForAccount) {
err = ErrJetStreamNotEnabledForAccount
} else {
err = &jsError{
apiErr: info.Error,
}
}
return nil, err
}
Expand Down
7 changes: 7 additions & 0 deletions test/js_test.go
Expand Up @@ -134,6 +134,9 @@ func TestJetStreamNotAccountEnabled(t *testing.T) {
t.Fatalf("Expected: %v, got: %v", expectedMessage, apierr.Error())
}

// an APIError also implements the JetStreamError interface.
var _ nats.JetStreamError = &nats.APIError{}

// matching arbitrary custom error via errors.Is(...)
customErr := &nats.APIError{ErrorCode: expected}
if ok := errors.Is(customErr, nats.ErrJetStreamNotEnabledForAccount); !ok {
Expand All @@ -143,6 +146,10 @@ func TestJetStreamNotAccountEnabled(t *testing.T) {
if ok := errors.Is(customErr, nats.ErrJetStreamNotEnabledForAccount); ok {
t.Fatal("Expected to not match ErrJetStreamNotEnabled")
}
var cerr nats.JetStreamError
if ok := errors.As(customErr, &cerr); !ok {
t.Fatal("Expected custom error to be a JetStreamError")
}

// matching to concrete type via errors.As(...)
var aerr *nats.APIError
Expand Down

0 comments on commit 8fee091

Please sign in to comment.