-
Notifications
You must be signed in to change notification settings - Fork 18
/
errors.go
263 lines (226 loc) · 6.27 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
// Tideland Go Library - Errors
//
// Copyright (C) 2013-2017 Frank Mueller / Tideland / Oldenburg / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.
package errors
//--------------------
// IMPORTS
//--------------------
import (
"fmt"
"path"
"runtime"
"strings"
)
//--------------------
// MESSAGES
//--------------------
// Messages contains the message strings for the the error codes.
type Messages map[int]string
// Format returns the formatted error message for code with the
// given arguments.
func (m Messages) Format(code int, args ...interface{}) string {
if m == nil || m[code] == "" {
if len(args) == 0 {
return fmt.Sprintf("[ERRORS:999] invalid error code '%d'", code)
}
format := fmt.Sprintf("%v", args[0])
return fmt.Sprintf(format, args[1:]...)
}
format := m[code]
return fmt.Sprintf(format, args...)
}
//--------------------
// CONSTANTS
//--------------------
// Error codes of the errors package.
const (
ErrInvalidErrorType = iota + 1
ErrNotYetImplemented
ErrDeprecated
)
var errorMessages = Messages{
ErrInvalidErrorType: "invalid error type: %T %q",
ErrNotYetImplemented: "feature is not yet implemented: %q",
ErrDeprecated: "feature is deprecated: %q",
}
//--------------------
// ERROR
//--------------------
// errorBox encapsulates an error.
type errorBox struct {
err error
code int
msg string
info *callInfo
}
// newErrorBox creates an initialized error box.
func newErrorBox(err error, code int, msgs Messages, args ...interface{}) *errorBox {
return &errorBox{
err: err,
code: code,
msg: msgs.Format(code, args...),
info: retrieveCallInfo(),
}
}
// Error implements the error interface.
func (eb *errorBox) Error() string {
if eb.err != nil {
return fmt.Sprintf("[%s:%03d] %s: %v", eb.info.packagePart, eb.code, eb.msg, eb.err)
}
return fmt.Sprintf("[%s:%03d] %s", eb.info.packagePart, eb.code, eb.msg)
}
// errorCollection bundles multiple errors.
type errorCollection struct {
errs []error
}
// Error implements the error interface.
func (ec *errorCollection) Error() string {
errMsgs := make([]string, len(ec.errs))
for i, err := range ec.errs {
errMsgs[i] = err.Error()
}
return strings.Join(errMsgs, "\n")
}
// Annotate creates an error wrapping another one together with a
// a code.
func Annotate(err error, code int, msgs Messages, args ...interface{}) error {
return newErrorBox(err, code, msgs, args...)
}
// New creates an error with the given code.
func New(code int, msgs Messages, args ...interface{}) error {
return newErrorBox(nil, code, msgs, args...)
}
// Collect collects multiple errors into one.
func Collect(errs ...error) error {
return &errorCollection{
errs: errs,
}
}
// Valid returns true if it is a valid error generated by
// this package.
func Valid(err error) bool {
_, ok := err.(*errorBox)
return ok
}
// IsError checks if an error is one created by this
// package and has the passed code
func IsError(err error, code int) bool {
if e, ok := err.(*errorBox); ok {
return e.code == code
}
return false
}
// Annotated returns the possibly annotated error. In case of
// a different error an invalid type error is returned.
func Annotated(err error) error {
if e, ok := err.(*errorBox); ok {
return e.err
}
return New(ErrInvalidErrorType, errorMessages, err, err)
}
// Location returns the package and the file name as well as the line
// number of the error.
func Location(err error) (string, string, int, error) {
if e, ok := err.(*errorBox); ok {
return e.info.packageName, e.info.fileName, e.info.line, nil
}
return "", "", 0, New(ErrInvalidErrorType, errorMessages, err, err)
}
// Stack returns a slice of errors down to the first
// non-errors error in case of annotated errors.
func Stack(err error) []error {
if eb, ok := err.(*errorBox); ok {
return append([]error{eb}, Stack(eb.err)...)
}
return []error{err}
}
// All returns a slice of errors in case of collected errors.
func All(err error) []error {
if ec, ok := err.(*errorCollection); ok {
all := make([]error, len(ec.errs))
copy(all, ec.errs)
return all
}
return []error{err}
}
// DoAll iterates the passed function over all stacked
// or collected errors or simply the one that's passed.
func DoAll(err error, f func(error)) {
switch terr := err.(type) {
case *errorBox:
for _, serr := range Stack(err) {
f(serr)
}
case *errorCollection:
for _, aerr := range All(err) {
f(aerr)
}
default:
f(terr)
}
}
// IsInvalidTypeError checks if an error signals an invalid
// type in case of testing for an annotated error.
func IsInvalidTypeError(err error) bool {
return IsError(err, ErrInvalidErrorType)
}
// NotYetImplementedError returns the common error for a not yet
// implemented feature.
func NotYetImplementedError(feature string) error {
return New(ErrNotYetImplemented, errorMessages, feature)
}
// IsNotYetImplementedError checks if an error signals a not yet
// implemented feature.
func IsNotYetImplementedError(err error) bool {
return IsError(err, ErrNotYetImplemented)
}
// DeprecatedError returns the common error for a deprecated
// feature.
func DeprecatedError(feature string) error {
return New(ErrDeprecated, errorMessages, feature)
}
// IsDeprecatedError checks if an error signals deprecated
// feature.
func IsDeprecatedError(err error) bool {
return IsError(err, ErrDeprecated)
}
//--------------------
// PRIVATE HELPERS
//--------------------
// callInfo bundles the info about the call environment
// when a logging statement occurred.
type callInfo struct {
packageName string
packagePart string
fileName string
funcName string
line int
}
// retrieveCallInfo
func retrieveCallInfo() *callInfo {
pc, file, line, _ := runtime.Caller(3)
_, fileName := path.Split(file)
parts := strings.Split(runtime.FuncForPC(pc).Name(), ".")
pl := len(parts)
packageName := ""
funcName := parts[pl-1]
if parts[pl-2][0] == '(' {
funcName = parts[pl-2] + "." + funcName
packageName = strings.Join(parts[0:pl-2], ".")
} else {
packageName = strings.Join(parts[0:pl-1], ".")
}
packageParts := strings.Split(packageName, "/")
packagePart := strings.ToUpper(packageParts[len(packageParts)-1])
return &callInfo{
packageName: packageName,
packagePart: packagePart,
fileName: fileName,
funcName: funcName,
line: line,
}
}
// EOF