github.com/cockroachdb/errors@v1.11.1/errbase/unwrap_test.go (about) 1 // Copyright 2019 The Cockroach Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 12 // implied. See the License for the specific language governing 13 // permissions and limitations under the License. 14 15 package errbase_test 16 17 import ( 18 "errors" 19 "fmt" 20 "testing" 21 22 "github.com/cockroachdb/errors/errbase" 23 "github.com/cockroachdb/errors/testutils" 24 pkgErr "github.com/pkg/errors" 25 ) 26 27 // This test demonstrates how to use errbase.UnwrapOnce and errbase.UnwrapAll to 28 // access causes. 29 func TestUnwrap(t *testing.T) { 30 tt := testutils.T{T: t} 31 32 err := errors.New("hello") 33 34 tt.CheckEqual(errbase.UnwrapOnce(err), nil) 35 tt.CheckEqual(errbase.UnwrapAll(err), err) 36 37 // WithMessage is guaranteed to add just one layer of wrapping. 38 err2 := pkgErr.WithMessage(err, "woo") 39 40 tt.CheckEqual(errbase.UnwrapOnce(err2), err) 41 tt.CheckEqual(errbase.UnwrapAll(err2), err) 42 43 err3 := pkgErr.WithMessage(err2, "woo") 44 45 tt.CheckEqual(errbase.UnwrapOnce(err3), err2) 46 tt.CheckEqual(errbase.UnwrapAll(err3), err) 47 } 48 49 // This test demonstrates how errbase.UnwrapOnce/errbase.UnwrapAll are able to use 50 // either Cause() or errbase.Unwrap(). 51 func TestMixedErrorWrapping(t *testing.T) { 52 tt := testutils.T{T: t} 53 54 err := errors.New("hello") 55 err2 := pkgErr.WithMessage(err, "woo") 56 err3 := &myWrapper{cause: err2} 57 58 tt.CheckEqual(errbase.UnwrapOnce(err3), err2) 59 tt.CheckEqual(errbase.UnwrapAll(err3), err) 60 } 61 62 func TestMultiErrorUnwrap(t *testing.T) { 63 tt := testutils.T{T: t} 64 65 err := errors.New("hello") 66 err2 := pkgErr.WithMessage(err, "woo") 67 err3 := fmt.Errorf("%w %w", err, err2) 68 69 tt.CheckEqual(errbase.UnwrapOnce(err3), nil) 70 tt.CheckEqual(errbase.UnwrapAll(err3), err3) 71 tt.CheckDeepEqual(errbase.UnwrapMulti(err3), []error{err, err2}) 72 } 73 74 type myWrapper struct{ cause error } 75 76 func (w *myWrapper) Error() string { return w.cause.Error() } 77 func (w *myWrapper) Unwrap() error { return w.cause }