/
is.go
52 lines (45 loc) · 1.39 KB
/
is.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
package ex
import "errors"
// Is is a helper function that returns if an error is an ex.
//
// It will handle if the err is an exception, a multi-error or a regular error.
// "Isness" is evaluated by if the class of the exception matches the class of the cause
func Is(err interface{}, cause error) bool {
if err == nil || cause == nil {
return false
}
if typed := As(err); typed != nil {
if typed.Class == nil {
return false
}
if causeTyped := As(cause); causeTyped != nil {
if causeTyped.Class == nil {
return false
}
return typed.Class == causeTyped.Class
}
return (typed.Class == cause) || (typed.Class.Error() == cause.Error()) || errors.Is(typed.Class, cause)
}
if typed, ok := err.(ClassProvider); ok {
return typed.Class() == cause || (typed.Class().Error() == cause.Error()) || errors.Is(typed.Class(), cause)
}
// handle the case of multi-exceptions
if multiTyped, ok := err.(Multi); ok {
for _, multiErr := range multiTyped {
if Is(multiErr, cause) {
return true
}
}
return false
}
// handle regular errors
if typed, ok := err.(error); ok && typed != nil {
return (err == cause) || (typed.Error() == cause.Error()) || errors.Is(typed, cause)
}
// handle ???
return err == cause
}