Skip to content

Commit afeeccd

Browse files
zmb3cpuschma
andauthored
feat: add support for Go 1.13's errors.Is/As functions (#461)
ldap.Error wraps an underlying error, but doesn't interoperate with errors.Is or errors.As since it doesn't expose an Unwrap method. This change makes it easier to detect things like an LDAP error caused due to a network timeout. Co-authored-by: Christopher Puschmann <[email protected]>
1 parent 7f97b82 commit afeeccd

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

v3/error.go

+2
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@ func (e *Error) Error() string {
192192
return fmt.Sprintf("LDAP Result Code %d %q: %s", e.ResultCode, LDAPResultCodeMap[e.ResultCode], e.Err.Error())
193193
}
194194

195+
func (e *Error) Unwrap() error { return e.Err }
196+
195197
// GetLDAPError creates an Error out of a BER packet representing a LDAPResult
196198
// The return is an error object. It can be casted to a Error structure.
197199
// 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)