blob: 0f5e5850af87d5984bb4c6f137da10064c1e3b96 [file] [log] [blame]
Damien Neil01b51b42020-01-17 13:40:51 -08001// Copyright 2020 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// +build !go1.13
6
7package errors
8
9import "reflect"
10
11// Is is a copy of Go 1.13's errors.Is for use with older Go versions.
12func Is(err, target error) bool {
13 if target == nil {
14 return err == target
15 }
16
17 isComparable := reflect.TypeOf(target).Comparable()
18 for {
19 if isComparable && err == target {
20 return true
21 }
22 if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {
23 return true
24 }
25 // TODO: consider supporing target.Is(err). This would allow
26 // user-definable predicates, but also may allow for coping with sloppy
27 // APIs, thereby making it easier to get away with them.
28 if err = unwrap(err); err == nil {
29 return false
30 }
31 }
32}
33
34func unwrap(err error) error {
35 u, ok := err.(interface {
36 Unwrap() error
37 })
38 if !ok {
39 return nil
40 }
41 return u.Unwrap()
42}