David K. Bainbridge | e05cf0c | 2021-08-19 03:16:50 +0000 | [diff] [blame] | 1 | // 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 | |
| 7 | package errors |
| 8 | |
| 9 | import "reflect" |
| 10 | |
| 11 | // Is is a copy of Go 1.13's errors.Is for use with older Go versions. |
| 12 | func 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 | if err = unwrap(err); err == nil { |
| 26 | return false |
| 27 | } |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | func unwrap(err error) error { |
| 32 | u, ok := err.(interface { |
| 33 | Unwrap() error |
| 34 | }) |
| 35 | if !ok { |
| 36 | return nil |
| 37 | } |
| 38 | return u.Unwrap() |
| 39 | } |