Skip to content
This repository has been archived by the owner on Dec 1, 2021. It is now read-only.

Commit

Permalink
Add support for Go 1.13 error chains (#206)
Browse files Browse the repository at this point in the history
* 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.
  • Loading branch information
jayschwa authored and aperezg committed Nov 9, 2019
1 parent 91f1693 commit 7f95ac1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
6 changes: 6 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -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':
Expand Down Expand Up @@ -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':
Expand Down
16 changes: 16 additions & 0 deletions go113_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}

3 comments on commit 7f95ac1

@cee-dub
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any plans to create a new release with this addition?

@mingrammer
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

@tuanpavn
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Please sign in to comment.