Skip to content

Commit

Permalink
Merge pull request #1082 from nats-io/auth-error-is
Browse files Browse the repository at this point in the history
Add natsProtoErr that can be used with errors.Is
  • Loading branch information
wallyqs committed Sep 15, 2022
2 parents 51ba8b3 + 275563c commit caf5af2
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
16 changes: 14 additions & 2 deletions nats.go
Expand Up @@ -2323,6 +2323,19 @@ func normalizeErr(line string) string {
return s
}

// natsProtoErr represents an -ERR protocol message sent by the server.
type natsProtoErr struct {
description string
}

func (nerr *natsProtoErr) Error() string {
return fmt.Sprintf("nats: %s", nerr.description)
}

func (nerr *natsProtoErr) Is(err error) bool {
return strings.ToLower(nerr.Error()) == err.Error()
}

// Send a connect protocol message to the server, issue user/password if
// applicable. Will wait for a flush to return from the server for error
// processing.
Expand Down Expand Up @@ -2377,8 +2390,7 @@ func (nc *Conn) sendConnect() error {
// in doReconnect()).
nc.processAuthError(authErr)
}

return errors.New("nats: " + proto)
return &natsProtoErr{proto}
}

// Notify that we got an unexpected protocol.
Expand Down
5 changes: 5 additions & 0 deletions test/auth_test.go
Expand Up @@ -14,6 +14,7 @@
package test

import (
"errors"
"fmt"
"strings"
"sync/atomic"
Expand Down Expand Up @@ -44,6 +45,10 @@ func TestAuth(t *testing.T) {
t.Fatalf("Expected error '%v', got '%v'", nats.ErrAuthorization, err)
}

if !errors.Is(err, nats.ErrAuthorization) {
t.Fatalf("Expected error '%v', got '%v'", nats.ErrAuthorization, err)
}

nc, err := nats.Connect("nats://derek:foo@127.0.0.1:8232")
if err != nil {
t.Fatal("Should have connected successfully with a token")
Expand Down
5 changes: 5 additions & 0 deletions test/cluster_test.go
Expand Up @@ -14,6 +14,7 @@
package test

import (
"errors"
"fmt"
"math"
"net"
Expand Down Expand Up @@ -193,6 +194,10 @@ func TestAuthServers(t *testing.T) {
t.Fatalf("Wrong error, wanted Auth failure, got '%s'\n", err)
}

if !errors.Is(err, nats.ErrAuthorization) {
t.Fatalf("Expected error '%v', got '%v'", nats.ErrAuthorization, err)
}

// Test that we can connect to a subsequent correct server.
var authServers = []string{
"nats://127.0.0.1:1222",
Expand Down

0 comments on commit caf5af2

Please sign in to comment.