Skip to content

Commit 64833e3

Browse files
committed
Add support for Go 1.13's errors.Is/As functions
ldap.Error wraps an underlying error, but doesn't interoperate with errors.Is or errors.As. This change makes it easier to detect things like an LDAP error caused due to a network timeout.
1 parent bbc2f21 commit 64833e3

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

v3/error.go

+9
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package ldap
22

33
import (
4+
"errors"
45
"fmt"
56

67
ber "github.com/go-asn1-ber/asn1-ber"
@@ -192,6 +193,14 @@ func (e *Error) Error() string {
192193
return fmt.Sprintf("LDAP Result Code %d %q: %s", e.ResultCode, LDAPResultCodeMap[e.ResultCode], e.Err.Error())
193194
}
194195

196+
func (e *Error) Is(target error) bool {
197+
return errors.Is(e.Err, target)
198+
}
199+
200+
func (e *Error) As(target interface{}) bool {
201+
return errors.As(e.Err, target)
202+
}
203+
195204
// GetLDAPError creates an Error out of a BER packet representing a LDAPResult
196205
// The return is an error object. It can be casted to a Error structure.
197206
// This function returns nil if resultCode in the LDAPResult sequence is success(0).

v3/error_test.go

+19
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package ldap
22

33
import (
44
"errors"
5+
"io"
56
"net"
67
"strings"
78
"testing"
@@ -103,6 +104,24 @@ func TestGetLDAPErrorInvalidResponse(t *testing.T) {
103104
}
104105
}
105106

107+
func TestErrorIs(t *testing.T) {
108+
err := NewError(ErrorNetwork, io.EOF)
109+
if !errors.Is(err, io.EOF) {
110+
t.Errorf("Expected an io.EOF error: %v", err)
111+
}
112+
}
113+
114+
func TestErrorAs(t *testing.T) {
115+
var netErr net.InvalidAddrError = "invalid addr"
116+
err := NewError(ErrorNetwork, netErr)
117+
118+
var target net.InvalidAddrError
119+
ok := errors.As(err, &target)
120+
if !ok {
121+
t.Error("Expected an InvalidAddrError")
122+
}
123+
}
124+
106125
// TestGetLDAPErrorSuccess tests parsing of a result with no error (resultCode == 0).
107126
func TestGetLDAPErrorSuccess(t *testing.T) {
108127
bindResponse := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationBindResponse, nil, "Bind Response")

0 commit comments

Comments
 (0)