This repository has been archived by the owner on Oct 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
error.go
88 lines (74 loc) · 1.76 KB
/
error.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package maperr
import (
"errors"
"fmt"
)
// Error which exposes a method that determines if the error
// can be considered equal or not
type Error interface {
error
Equal(error) bool
Hashable() error
Is(err error) bool
}
// Errorf returns an error which persists
func Errorf(format string, args ...interface{}) Error {
return newFormattedError(format, args...)
}
// castError cast an error to maperr.Error when possible
// otherwise creates a new maperr.Error
func castError(err error) Error {
if err == nil {
return nil
}
var mapError Error
if errors.As(err, &mapError) {
return mapError
}
return NewError(err.Error())
}
// NewError instantiates an Error with no formatting
func NewError(errText string) Error {
return Errorf(errText)
}
// formattedError is a error that holds the format
// from which the error was generated
type formattedError struct {
format string
args []interface{}
err error
}
// newFormattedError return instance of formattedError
func newFormattedError(format string, args ...interface{}) formattedError {
return formattedError{
format: format,
args: args,
err: fmt.Errorf(format, args...),
}
}
// Error return the actual error
func (fe formattedError) Error() string {
return fe.err.Error()
}
// Unwrap return the actual error
func (fe formattedError) Unwrap() error {
return fe.err
}
// Error return the hashable error
func (fe formattedError) Hashable() error {
return fe.err
}
// Is is an alias for Equal added to support go 1.13 errors
func (fe formattedError) Is(err error) bool {
return fe.Equal(err)
}
func (fe formattedError) Equal(err error) bool {
if err == nil {
return false
}
var ferr formattedError
if errors.As(err, &ferr) {
return fe.format == ferr.format
}
return fe.Error() == err.Error()
}