-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors.go
218 lines (190 loc) · 6.07 KB
/
errors.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/*
The MIT License (MIT)
Copyright (c) 2013 Frank Laub
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// Package ergo contains generalized error utilities.
package ergo
import (
"bytes"
"fmt"
"log"
"runtime"
"text/template"
)
// ErrCode defines a type for error codes.
type ErrCode int
// ErrInfo is a collection of named values associated with an error.
type ErrInfo map[string]interface{}
// DomainMap is used to define message formats associated with error coddes.
type DomainMap map[ErrCode]string
// FormatFunc is a function that users can implement to define their own message formats.
type FormatFunc func(err *Error) string
// Error is a generic error designed to be serializable and provide
// additional information for developers while keeping
// friendly messages distinct for end users.
type Error struct {
_struct bool `codec:",omitempty"` // set omitempty for every field
// The domain of this error.
Domain string `json:",omitempty"`
// The error code of this error.
Code ErrCode `json:",omitempty"`
// A collection of named values associated with this error.
Info ErrInfo `json:",omitempty"`
// Additional context to help developers determine the source of an error.
// In go, this is a stack trace. In C++, this could be file:line.
Context string `json:",omitempty"`
// Used for defining a chain of errors.
// The innermost error represents the original error.
Inner *Error `json:",omitempty"`
}
var (
domains = make(map[string]FormatFunc)
)
func init() {
DomainFunc("go", func(err *Error) string {
return "Error: " + err.Info["_err"].(string)
})
}
// New creates a new error.
// "skip" is used to skip stack frames,
// a value of 0 means the stack will start at the call site of Make().
// "args" is a set of pairs to be used to populate "Info":
// first is the key, second is the value.
func New(skip int, domain string, code ErrCode, args ...interface{}) *Error {
err := &Error{
Domain: domain,
Code: code,
Info: make(ErrInfo),
Context: stackTrace(skip + 2),
}
var name string
for _, arg := range args {
if name == "" {
name = arg.(string)
} else {
err.Info[name] = arg
name = ""
}
}
return err
}
func _Wrap(skip int, err error, args ...interface{}) *Error {
sys := []interface{}{"_err", err.Error()}
return New(skip+1, "go", 0, append(sys, args...)...)
}
// Wrap takes a generic interface "x" and returns an Error.
// If "x" is nil, nil is returned.
// If "x" is an Error, this is returned.
// If "x" implements the standard error interface, a standard Error is generated.
// Otherwise, "x" is converted into a string and used to generate a standard Error.
func Wrap(x interface{}, args ...interface{}) *Error {
if x == nil {
return nil
}
if err, ok := x.(*Error); ok {
return err
}
if err, ok := x.(error); ok {
return _Wrap(1, err, args...)
}
return _Wrap(1, fmt.Errorf("%v", x), args...)
}
// Chain links an inner error to an outer one.
// The result is the outer error.
func Chain(inner error, err *Error) error {
if inner == nil {
return nil
}
err.Inner = Wrap(inner)
return err
}
// Cause returns the cause of the error,
// which is the innermost error in a chain.
func Cause(err error) error {
if ergo, ok := err.(*Error); ok {
if ergo.Inner == nil {
return ergo
}
return Cause(ergo.Inner)
}
return err
}
// DomainFunc allows users to define custom domains.
// This is a low-level API.
func DomainFunc(name string, fn FormatFunc) {
_, ok := domains[name]
if ok {
log.Panicf("Domain conflict: %v", name)
}
domains[name] = fn
}
// Domain allows users to define custom domains.
// A domain represents a set of error codes and their associated
// message formats. The format string is processed by text/template.
func Domain(name string, domain DomainMap) {
tmpls := make(map[ErrCode]*template.Template)
for code, text := range domain {
name := fmt.Sprintf("[%v:%d]", name, code)
tmpl := template.Must(template.New(name).Parse(text))
tmpls[code] = tmpl
}
DomainFunc(name, func(err *Error) string {
tmpl, ok := tmpls[err.Code]
if !ok {
return "Unknown error"
}
var buf bytes.Buffer
terr := tmpl.Execute(&buf, err.Info)
if terr != nil {
panic(terr)
}
return buf.String()
})
}
func stackTrace(skip int) string {
buf := bytes.Buffer{}
stack := [50]uintptr{}
n := runtime.Callers(skip+1, stack[:])
for _, pc := range stack[:n] {
fn := runtime.FuncForPC(pc)
file, line := fn.FileLine(pc)
fmt.Fprintf(&buf, "%v:%v\n", file, line)
fmt.Fprintf(&buf, "\t%v\n", fn.Name())
}
return buf.String()
}
// Message returns the friendly error message without context.
// This is appropriate for displaying to end users.
func (err *Error) Message() string {
domain, ok := domains[err.Domain]
if ok {
return domain(err)
}
return fmt.Sprintf("Domain missing: [%v:%d] %v",
err.Domain, err.Code, err.Info)
}
// Error implements error.Error().
// The entire chain along with context is returned.
// Use Message() to display end user friendly messages.
func (err *Error) Error() string {
str := fmt.Sprintf("[%v:%d] %v\n%v",
err.Domain, err.Code, err.Message(), err.Context)
if err.Inner == nil {
return str
}
return err.Inner.Error() + "\n" + str
}