Debian Codegraph @

errors.go

raw
1 // Copyright 2014 Roger Peppe.
2 // See LICENCE file for details.
3
4 // Package errgo provides a way to create
5 // and diagnose errors. It is compatible with
6 // the usual Go error idioms but adds a way to wrap errors
7 // so that they record source location information
8 // while retaining a consistent way for code to
9 // inspect errors to find out particular problems.
10 //
11 package errgo
12
13 import (
14 "bytes"
15 "fmt"
16 "log"
17 "runtime"
18 )
19
20 const debug = false
21
22 // Err holds a description of an error along with information about
23 // where the error was created.
24 //
25 // It may be embedded in custom error types to add
26 // extra information that this errors package can
27 // understand.
28 type Err struct {
29 // Message_ holds the text of the error message. It may be empty
30 // if Underlying is set.
31 Message_ string
32
33 // Cause_ holds the cause of the error as returned
34 // by the Cause method.
35 Cause_ error
36
37 // Underlying_ holds the underlying error, if any.
38 Underlying_ error
39
40 // File and Line identify the source code location where the error was
41 // created.
42 File string
43 Line int
44 }
45
46 // Location implements Locationer.
47 func (e *Err) Location() (file string, line int) {
48 return e.File, e.Line
49 }
50
51 // Underlying returns the underlying error if any.
52 func (e *Err) Underlying() error {
53 return e.Underlying_
54 }
55
56 // Cause implements Causer.
57 func (e *Err) Cause() error {
58 return e.Cause_
59 }
60
61 // Message returns the top level error message.
62 func (e *Err) Message() string {
63 return e.Message_
64 }
65
66 // Error implements error.Error.
67 func (e *Err) Error() string {
68 switch {
69 case e.Message_ == "" && e.Underlying_ == nil:
70 return "<no error>"
71 case e.Message_ == "":
72 return e.Underlying_.Error()
73 case e.Underlying_ == nil:
74 return e.Message_
75 }
76 return fmt.Sprintf("%s: %v", e.Message_, e.Underlying_)
77 }
78
79 // GoString returns the details of the receiving error
80 // message, so that printing an error with %#v will
81 // produce useful information.
82 func (e *Err) GoString() string {
83 return Details(e)
84 }
85
86 // Causer is the type of an error that may provide
87 // an error cause for error diagnosis. Cause may return
88 // nil if there is no cause (for example because the
89 // cause has been masked).
90 type Causer interface {
91 Cause() error
92 }
93
94 // Wrapper is the type of an error that wraps another error. It is
95 // exposed so that external types may implement it, but should in
96 // general not be used otherwise.
97 type Wrapper interface {
98 // Message returns the top level error message,
99 // not including the message from the underlying
100 // error.
101 Message() string
102
103 // Underlying returns the underlying error, or nil
104 // if there is none.
105 Underlying() error
106 }
107
108 // Locationer can be implemented by any error type
109 // that wants to expose the source location of an error.
110 type Locationer interface {
111 // Location returns the name of the file and the line
112 // number associated with an error.
113 Location() (file string, line int)
114 }
115
116 // Details returns information about the stack of
117 // underlying errors wrapped by err, in the format:
118 //
119 // [{filename:99: error one} {otherfile:55: cause of error one}]
120 //
121 // The details are found by type-asserting the error to
122 // the Locationer, Causer and Wrapper interfaces.
123 // Details of the underlying stack are found by
124 // recursively calling Underlying when the
125 // underlying error implements Wrapper.
126 func Details(err error) string {
127 if err == nil {
128 return "[]"
129 }
130 var s []byte
131 s = append(s, '[')
132 for {
133 s = append(s, '{')
134 if err, ok := err.(Locationer); ok {
135 file, line := err.Location()
136 if file != "" {
137 s = append(s, fmt.Sprintf("%s:%d", file, line)...)
138 s = append(s, ": "...)
139 }
140 }
141 if cerr, ok := err.(Wrapper); ok {
142 s = append(s, cerr.Message()...)
143 err = cerr.Underlying()
144 } else {
145 s = append(s, err.Error()...)
146 err = nil
147 }
148 if debug {
149 if err, ok := err.(Causer); ok {
150 if cause := err.Cause(); cause != nil {
151 s = append(s, fmt.Sprintf("=%T", cause)...)
152 s = append(s, Details(cause)...)
153 }
154 }
155 }
156 s = append(s, '}')
157 if err == nil {
158 break
159 }
160 s = append(s, ' ')
161 }
162 s = append(s, ']')
163 return string(s)
164 }
165
166 // SetLocation records the source location of the error by setting
167 // e.Location, at callDepth stack frames above the call.
168 func (e *Err) SetLocation(callDepth int) {
169 _, file, line, _ := runtime.Caller(callDepth + 1)
170 e.File, e.Line = file, line
171 }
172
173 func setLocation(err error, callDepth int) {
174 if e, _ := err.(*Err); e != nil {
175 e.SetLocation(callDepth + 1)
176 }
177 }
178
179 // New returns a new error with the given error message and no cause. It
180 // is a drop-in replacement for errors.New from the standard library.
181 func New(s string) error {
182 err := &Err{Message_: s}
183 err.SetLocation(1)
184 return err
185 }
186
187 // Newf returns a new error with the given printf-formatted error
188 // message and no cause.
189 func Newf(f string, a ...interface{}) error {
190 err := &Err{Message_: fmt.Sprintf(f, a...)}
191 err.SetLocation(1)
192 return err
193 }
194
195 // match returns whether any of the given
196 // functions returns true when called with err as an
197 // argument.
198 func match(err error, pass ...func(error) bool) bool {
199 for _, f := range pass {
200 if f(err) {
201 return true
202 }
203 }
204 return false
205 }
206
207 // Is returns a function that returns whether the
208 // an error is equal to the given error.
209 // It is intended to be used as a "pass" argument
210 // to Mask and friends; for example:
211 //
212 // return errgo.Mask(err, errgo.Is(http.ErrNoCookie))
213 //
214 // would return an error with an http.ErrNoCookie cause
215 // only if that was err's diagnosis; otherwise the diagnosis
216 // would be itself.
217 func Is(err error) func(error) bool {
218 return func(err1 error) bool {
219 return err == err1
220 }
221 }
222
223 // Any returns true. It can be used as an argument to Mask
224 // to allow any diagnosis to pass through to the wrapped
225 // error.
226 func Any(error) bool {
227 return true
228 }
229
230 // NoteMask returns an Err that has the given underlying error,
231 // with the given message added as context, and allowing
232 // the cause of the underlying error to pass through into
233 // the result if allowed by the specific pass functions
234 // (see Mask for an explanation of the pass parameter).
235 func NoteMask(underlying error, msg string, pass ...func(error) bool) error {
236 err := noteMask(underlying, msg, pass...)
237 setLocation(err, 1)
238 return err
239 }
240
241 // noteMask is exactly like NoteMask except it doesn't set the location
242 // of the returned error, so that we can avoid setting it twice
243 // when it's used in other functions.
244 func noteMask(underlying error, msg string, pass ...func(error) bool) error {
245 newErr := &Err{
246 Underlying_: underlying,
247 Message_: msg,
248 }
249 if len(pass) > 0 {
250 if cause := Cause(underlying); match(cause, pass...) {
251 newErr.Cause_ = cause
252 }
253 }
254 if debug {
255 if newd, oldd := newErr.Cause_, Cause(underlying); newd != oldd {
256 log.Printf("Mask cause %[1]T(%[1]v)->%[2]T(%[2]v)", oldd, newd)
257 log.Printf("call stack: %s", callers(0, 20))
258 log.Printf("len(allow) == %d", len(pass))
259 log.Printf("old error %#v", underlying)
260 log.Printf("new error %#v", newErr)
261 }
262 }
263 newErr.SetLocation(1)
264 return newErr
265 }
266
267 // Mask returns an Err that wraps the given underyling error. The error
268 // message is unchanged, but the error location records the caller of
269 // Mask.
270 //
271 // If err is nil, Mask returns nil.
272 //
273 // By default Mask conceals the cause of the wrapped error, but if
274 // pass(Cause(err)) returns true for any of the provided pass functions,
275 // the cause of the returned error will be Cause(err).
276 //
277 // For example, the following code will return an error whose cause is
278 // the error from the os.Open call when (and only when) the file does
279 // not exist.
280 //
281 // f, err := os.Open("non-existent-file")
282 // if err != nil {
283 // return errgo.Mask(err, os.IsNotExist)
284 // }
285 //
286 // In order to add context to returned errors, it
287 // is conventional to call Mask when returning any
288 // error received from elsewhere.
289 //
290 func Mask(underlying error, pass ...func(error) bool) error {
291 if underlying == nil {
292 return nil
293 }
294 err := noteMask(underlying, "", pass...)
295 setLocation(err, 1)
296 return err
297 }
298
299 // Notef returns an Error that wraps the given underlying
300 // error and adds the given formatted context message.
301 // The returned error has no cause (use NoteMask
302 // or WithCausef to add a message while retaining a cause).
303 func Notef(underlying error, f string, a ...interface{}) error {
304 err := noteMask(underlying, fmt.Sprintf(f, a...))
305 setLocation(err, 1)
306 return err
307 }
308
309 // MaskFunc returns an equivalent of Mask that always allows the
310 // specified causes in addition to any causes specified when the
311 // returned function is called.
312 //
313 // It is defined for convenience, for example when all calls to Mask in
314 // a given package wish to allow the same set of causes to be returned.
315 func MaskFunc(allow ...func(error) bool) func(error, ...func(error) bool) error {
316 return func(err error, allow1 ...func(error) bool) error {
317 var allowEither []func(error) bool
318 if len(allow1) > 0 {
319 // This is more efficient than using a function literal,
320 // because the compiler knows that it doesn't escape.
321 allowEither = make([]func(error) bool, len(allow)+len(allow1))
322 copy(allowEither, allow)
323 copy(allowEither[len(allow):], allow1)
324 } else {
325 allowEither = allow
326 }
327 err = Mask(err, allowEither...)
328 setLocation(err, 1)
329 return err
330 }
331 }
332
333 // WithCausef returns a new Error that wraps the given
334 // (possibly nil) underlying error and associates it with
335 // the given cause. The given formatted message context
336 // will also be added. If underlying is nil and f is empty and has no arguments,
337 // the message will be the same as the cause.
338 func WithCausef(underlying, cause error, f string, a ...interface{}) error {
339 var msg string
340 if underlying == nil && f == "" && len(a) == 0 && cause != nil {
341 msg = cause.Error()
342 } else {
343 msg = fmt.Sprintf(f, a...)
344 }
345 err := &Err{
346 Underlying_: underlying,
347 Cause_: cause,
348 Message_: msg,
349 }
350 err.SetLocation(1)
351 return err
352 }
353
354 // Cause returns the cause of the given error. If err does not
355 // implement Causer or its Cause method returns nil, it returns err itself.
356 //
357 // Cause is the usual way to diagnose errors that may have
358 // been wrapped by Mask or NoteMask.
359 func Cause(err error) error {
360 var diag error
361 if err, ok := err.(Causer); ok {
362 diag = err.Cause()
363 }
364 if diag != nil {
365 return diag
366 }
367 return err
368 }
369
370 // callers returns the stack trace of the goroutine that called it,
371 // starting n entries above the caller of callers, as a space-separated list
372 // of filename:line-number pairs with no new lines.
373 func callers(n, max int) []byte {
374 var b bytes.Buffer
375 prev := false
376 for i := 0; i < max; i++ {
377 _, file, line, ok := runtime.Caller(n + 1)
378 if !ok {
379 return b.Bytes()
380 }
381 if prev {
382 fmt.Fprintf(&b, " ")
383 }
384 fmt.Fprintf(&b, "%s:%d", file, line)
385 n++
386 prev = true
387 }
388 return b.Bytes()
389 }