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

Commit 7f95ac1

Browse files
jayschwaaperezg
authored andcommitted
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.
1 parent 91f1693 commit 7f95ac1

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

errors.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,9 @@ type withStack struct {
159159

160160
func (w *withStack) Cause() error { return w.error }
161161

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

247+
// Unwrap provides compatibility for Go 1.13 error chains.
248+
func (w *withMessage) Unwrap() error { return w.cause }
249+
244250
func (w *withMessage) Format(s fmt.State, verb rune) {
245251
switch verb {
246252
case 'v':

go113_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// +build go1.13
2+
3+
package errors
4+
5+
import (
6+
stdlib_errors "errors"
7+
"testing"
8+
)
9+
10+
func TestErrorChainCompat(t *testing.T) {
11+
err := stdlib_errors.New("error that gets wrapped")
12+
wrapped := Wrap(err, "wrapped up")
13+
if !stdlib_errors.Is(wrapped, err) {
14+
t.Errorf("Wrap does not support Go 1.13 error chains")
15+
}
16+
}

0 commit comments

Comments
 (0)