blob: 35b119aa345955efcd324f619b74d4fed6a3406c [file] [log] [blame]
David K. Bainbridge528b3182017-01-23 08:51:59 -08001// Copyright 2013, 2014 Canonical Ltd.
2// Licensed under the LGPLv3, see LICENCE file for details.
3
4/*
5[godoc-link-here]
6
7The juju/errors provides an easy way to annotate errors without losing the
8orginal error context.
9
10The exported `New` and `Errorf` functions are designed to replace the
11`errors.New` and `fmt.Errorf` functions respectively. The same underlying
12error is there, but the package also records the location at which the error
13was created.
14
15A primary use case for this library is to add extra context any time an
16error is returned from a function.
17
18 if err := SomeFunc(); err != nil {
19 return err
20 }
21
22This instead becomes:
23
24 if err := SomeFunc(); err != nil {
25 return errors.Trace(err)
26 }
27
28which just records the file and line number of the Trace call, or
29
30 if err := SomeFunc(); err != nil {
31 return errors.Annotate(err, "more context")
32 }
33
34which also adds an annotation to the error.
35
36When you want to check to see if an error is of a particular type, a helper
37function is normally exported by the package that returned the error, like the
38`os` package does. The underlying cause of the error is available using the
39`Cause` function.
40
41 os.IsNotExist(errors.Cause(err))
42
43The result of the `Error()` call on an annotated error is the annotations joined
44with colons, then the result of the `Error()` method for the underlying error
45that was the cause.
46
47 err := errors.Errorf("original")
48 err = errors.Annotatef(err, "context")
49 err = errors.Annotatef(err, "more context")
50 err.Error() -> "more context: context: original"
51
52Obviously recording the file, line and functions is not very useful if you
53cannot get them back out again.
54
55 errors.ErrorStack(err)
56
57will return something like:
58
59 first error
60 github.com/juju/errors/annotation_test.go:193:
61 github.com/juju/errors/annotation_test.go:194: annotation
62 github.com/juju/errors/annotation_test.go:195:
63 github.com/juju/errors/annotation_test.go:196: more context
64 github.com/juju/errors/annotation_test.go:197:
65
66The first error was generated by an external system, so there was no location
67associated. The second, fourth, and last lines were generated with Trace calls,
68and the other two through Annotate.
69
70Sometimes when responding to an error you want to return a more specific error
71for the situation.
72
73 if err := FindField(field); err != nil {
74 return errors.Wrap(err, errors.NotFoundf(field))
75 }
76
77This returns an error where the complete error stack is still available, and
78`errors.Cause()` will return the `NotFound` error.
79
80*/
81package errors