Browse Source

Add support for Go 1.13 error chains (#206)

* Add support for Go 1.13 error chains

Go 1.13 adds support for error chains to the standard libary's errors
package. The new standard library functions require an Unwrap method to
be provided by an error type. This change adds a new Unwrap method
(identical to the existing Cause method) to the unexported error types.
Jay Petacat 6 năm trước cách đây
mục cha
commit
7f95ac13ed
2 tập tin đã thay đổi với 22 bổ sung0 xóa
  1. 6 0
      errors.go
  2. 16 0
      go113_test.go

+ 6 - 0
errors.go

@@ -159,6 +159,9 @@ type withStack struct {
 
 func (w *withStack) Cause() error { return w.error }
 
+// Unwrap provides compatibility for Go 1.13 error chains.
+func (w *withStack) Unwrap() error { return w.error }
+
 func (w *withStack) Format(s fmt.State, verb rune) {
 	switch verb {
 	case 'v':
@@ -241,6 +244,9 @@ type withMessage struct {
 func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
 func (w *withMessage) Cause() error  { return w.cause }
 
+// Unwrap provides compatibility for Go 1.13 error chains.
+func (w *withMessage) Unwrap() error { return w.cause }
+
 func (w *withMessage) Format(s fmt.State, verb rune) {
 	switch verb {
 	case 'v':

+ 16 - 0
go113_test.go

@@ -0,0 +1,16 @@
+// +build go1.13
+
+package errors
+
+import (
+	stdlib_errors "errors"
+	"testing"
+)
+
+func TestErrorChainCompat(t *testing.T) {
+	err := stdlib_errors.New("error that gets wrapped")
+	wrapped := Wrap(err, "wrapped up")
+	if !stdlib_errors.Is(wrapped, err) {
+		t.Errorf("Wrap does not support Go 1.13 error chains")
+	}
+}