• Stars
    star
    1,382
  • Rank 34,014 (Top 0.7 %)
  • Language
    Go
  • License
    Other
  • Created over 10 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Common juju errors and functions to annotate errors. Based on juju/errgo

errors

import "github.com/juju/errors"

GoDoc

The juju/errors provides an easy way to annotate errors without losing the original error context.

The exported New and Errorf functions are designed to replace the errors.New and fmt.Errorf functions respectively. The same underlying error is there, but the package also records the location at which the error was created.

A primary use case for this library is to add extra context any time an error is returned from a function.

    if err := SomeFunc(); err != nil {
	    return err
	}

This instead becomes:

    if err := SomeFunc(); err != nil {
	    return errors.Trace(err)
	}

which just records the file and line number of the Trace call, or

    if err := SomeFunc(); err != nil {
	    return errors.Annotate(err, "more context")
	}

which also adds an annotation to the error.

When you want to check to see if an error is of a particular type, a helper function is normally exported by the package that returned the error, like the os package does. The underlying cause of the error is available using the Cause function.

os.IsNotExist(errors.Cause(err))

The result of the Error() call on an annotated error is the annotations joined with colons, then the result of the Error() method for the underlying error that was the cause.

err := errors.Errorf("original")
err = errors.Annotatef(err, "context")
err = errors.Annotatef(err, "more context")
err.Error() -> "more context: context: original"

Obviously recording the file, line and functions is not very useful if you cannot get them back out again.

errors.ErrorStack(err)

will return something like:

first error
github.com/juju/errors/annotation_test.go:193:
github.com/juju/errors/annotation_test.go:194: annotation
github.com/juju/errors/annotation_test.go:195:
github.com/juju/errors/annotation_test.go:196: more context
github.com/juju/errors/annotation_test.go:197:

The first error was generated by an external system, so there was no location associated. The second, fourth, and last lines were generated with Trace calls, and the other two through Annotate.

Sometimes when responding to an error you want to return a more specific error for the situation.

    if err := FindField(field); err != nil {
	    return errors.Wrap(err, errors.NotFoundf(field))
	}

This returns an error where the complete error stack is still available, and errors.Cause() will return the NotFound error.

func AlreadyExistsf

func AlreadyExistsf(format string, args ...interface{}) error

AlreadyExistsf returns an error which satisfies IsAlreadyExists().

func Annotate

func Annotate(other error, message string) error

Annotate is used to add extra context to an existing error. The location of the Annotate call is recorded with the annotations. The file, line and function are also recorded.

For example:

if err := SomeFunc(); err != nil {
    return errors.Annotate(err, "failed to frombulate")
}

func Annotatef

func Annotatef(other error, format string, args ...interface{}) error

Annotatef is used to add extra context to an existing error. The location of the Annotate call is recorded with the annotations. The file, line and function are also recorded.

For example:

if err := SomeFunc(); err != nil {
    return errors.Annotatef(err, "failed to frombulate the %s", arg)
}

func BadRequestf

func BadRequestf(format string, args ...interface{}) error

BadRequestf returns an error which satisfies IsBadRequest().

func Cause

func Cause(err error) error

Cause returns the cause of the given error. This will be either the original error, or the result of a Wrap or Mask call.

Cause is the usual way to diagnose errors that may have been wrapped by the other errors functions.

func DeferredAnnotatef

func DeferredAnnotatef(err *error, format string, args ...interface{})

DeferredAnnotatef annotates the given error (when it is not nil) with the given format string and arguments (like fmt.Sprintf). If *err is nil, DeferredAnnotatef does nothing. This method is used in a defer statement in order to annotate any resulting error with the same message.

For example:

defer DeferredAnnotatef(&err, "failed to frombulate the %s", arg)

func Details

func Details(err error) string

Details returns information about the stack of errors wrapped by err, in the format:

[{filename:99: error one} {otherfile:55: cause of error one}]

This is a terse alternative to ErrorStack as it returns a single line.

func ErrorStack

func ErrorStack(err error) string

ErrorStack returns a string representation of the annotated error. If the error passed as the parameter is not an annotated error, the result is simply the result of the Error() method on that error.

If the error is an annotated error, a multi-line string is returned where each line represents one entry in the annotation stack. The full filename from the call stack is used in the output.

first error
github.com/juju/errors/annotation_test.go:193:
github.com/juju/errors/annotation_test.go:194: annotation
github.com/juju/errors/annotation_test.go:195:
github.com/juju/errors/annotation_test.go:196: more context
github.com/juju/errors/annotation_test.go:197:

func Errorf

func Errorf(format string, args ...interface{}) error

Errorf creates a new annotated error and records the location that the error is created. This should be a drop in replacement for fmt.Errorf.

For example:

return errors.Errorf("validation failed: %s", message)

func Forbiddenf

func Forbiddenf(format string, args ...interface{}) error

Forbiddenf returns an error which satistifes IsForbidden()

func IsAlreadyExists

func IsAlreadyExists(err error) bool

IsAlreadyExists reports whether the error was created with AlreadyExistsf() or NewAlreadyExists().

func IsBadRequest

func IsBadRequest(err error) bool

IsBadRequest reports whether err was created with BadRequestf() or NewBadRequest().

func IsForbidden

func IsForbidden(err error) bool

IsForbidden reports whether err was created with Forbiddenf() or NewForbidden().

func IsMethodNotAllowed

func IsMethodNotAllowed(err error) bool

IsMethodNotAllowed reports whether err was created with MethodNotAllowedf() or NewMethodNotAllowed().

func IsNotAssigned

func IsNotAssigned(err error) bool

IsNotAssigned reports whether err was created with NotAssignedf() or NewNotAssigned().

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err was created with NotFoundf() or NewNotFound().

func IsNotImplemented

func IsNotImplemented(err error) bool

IsNotImplemented reports whether err was created with NotImplementedf() or NewNotImplemented().

func IsNotProvisioned

func IsNotProvisioned(err error) bool

IsNotProvisioned reports whether err was created with NotProvisionedf() or NewNotProvisioned().

func IsNotSupported

func IsNotSupported(err error) bool

IsNotSupported reports whether the error was created with NotSupportedf() or NewNotSupported().

func IsNotValid

func IsNotValid(err error) bool

IsNotValid reports whether the error was created with NotValidf() or NewNotValid().

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized reports whether err was created with Unauthorizedf() or NewUnauthorized().

func IsUserNotFound

func IsUserNotFound(err error) bool

IsUserNotFound reports whether err was created with UserNotFoundf() or NewUserNotFound().

func Mask

func Mask(other error) error

Mask hides the underlying error type, and records the location of the masking.

func Maskf

func Maskf(other error, format string, args ...interface{}) error

Mask masks the given error with the given format string and arguments (like fmt.Sprintf), returning a new error that maintains the error stack, but hides the underlying error type. The error string still contains the full annotations. If you want to hide the annotations, call Wrap.

func MethodNotAllowedf

func MethodNotAllowedf(format string, args ...interface{}) error

MethodNotAllowedf returns an error which satisfies IsMethodNotAllowed().

func New

func New(message string) error

New is a drop in replacement for the standard library errors module that records the location that the error is created.

For example:

return errors.New("validation failed")

func NewAlreadyExists

func NewAlreadyExists(err error, msg string) error

NewAlreadyExists returns an error which wraps err and satisfies IsAlreadyExists().

func NewBadRequest

func NewBadRequest(err error, msg string) error

NewBadRequest returns an error which wraps err that satisfies IsBadRequest().

func NewForbidden

func NewForbidden(err error, msg string) error

NewForbidden returns an error which wraps err that satisfies IsForbidden().

func NewMethodNotAllowed

func NewMethodNotAllowed(err error, msg string) error

NewMethodNotAllowed returns an error which wraps err that satisfies IsMethodNotAllowed().

func NewNotAssigned

func NewNotAssigned(err error, msg string) error

NewNotAssigned returns an error which wraps err that satisfies IsNotAssigned().

func NewNotFound

func NewNotFound(err error, msg string) error

NewNotFound returns an error which wraps err that satisfies IsNotFound().

func NewNotImplemented

func NewNotImplemented(err error, msg string) error

NewNotImplemented returns an error which wraps err and satisfies IsNotImplemented().

func NewNotProvisioned

func NewNotProvisioned(err error, msg string) error

NewNotProvisioned returns an error which wraps err that satisfies IsNotProvisioned().

func NewNotSupported

func NewNotSupported(err error, msg string) error

NewNotSupported returns an error which wraps err and satisfies IsNotSupported().

func NewNotValid

func NewNotValid(err error, msg string) error

NewNotValid returns an error which wraps err and satisfies IsNotValid().

func NewUnauthorized

func NewUnauthorized(err error, msg string) error

NewUnauthorized returns an error which wraps err and satisfies IsUnauthorized().

func NewUserNotFound

func NewUserNotFound(err error, msg string) error

NewUserNotFound returns an error which wraps err and satisfies IsUserNotFound().

func NotAssignedf

func NotAssignedf(format string, args ...interface{}) error

NotAssignedf returns an error which satisfies IsNotAssigned().

func NotFoundf

func NotFoundf(format string, args ...interface{}) error

NotFoundf returns an error which satisfies IsNotFound().

func NotImplementedf

func NotImplementedf(format string, args ...interface{}) error

NotImplementedf returns an error which satisfies IsNotImplemented().

func NotProvisionedf

func NotProvisionedf(format string, args ...interface{}) error

NotProvisionedf returns an error which satisfies IsNotProvisioned().

func NotSupportedf

func NotSupportedf(format string, args ...interface{}) error

NotSupportedf returns an error which satisfies IsNotSupported().

func NotValidf

func NotValidf(format string, args ...interface{}) error

NotValidf returns an error which satisfies IsNotValid().

func Trace

func Trace(other error) error

Trace adds the location of the Trace call to the stack. The Cause of the resulting error is the same as the error parameter. If the other error is nil, the result will be nil.

For example:

if err := SomeFunc(); err != nil {
    return errors.Trace(err)
}

func Unauthorizedf

func Unauthorizedf(format string, args ...interface{}) error

Unauthorizedf returns an error which satisfies IsUnauthorized().

func UserNotFoundf

func UserNotFoundf(format string, args ...interface{}) error

UserNotFoundf returns an error which satisfies IsUserNotFound().

func Wrap

func Wrap(other, newDescriptive error) error

Wrap changes the Cause of the error. The location of the Wrap call is also stored in the error stack.

For example:

if err := SomeFunc(); err != nil {
    newErr := &packageError{"more context", private_value}
    return errors.Wrap(err, newErr)
}

func Wrapf

func Wrapf(other, newDescriptive error, format string, args ...interface{}) error

Wrapf changes the Cause of the error, and adds an annotation. The location of the Wrap call is also stored in the error stack.

For example:

if err := SomeFunc(); err != nil {
    return errors.Wrapf(err, simpleErrorType, "invalid value %q", value)
}

type Err

type Err struct {
    // contains filtered or unexported fields
}

Err holds a description of an error along with information about where the error was created.

It may be embedded in custom error types to add extra information that this errors package can understand.

func NewErr

func NewErr(format string, args ...interface{}) Err

NewErr is used to return an Err for the purpose of embedding in other structures. The location is not specified, and needs to be set with a call to SetLocation.

For example:

type FooError struct {
    errors.Err
    code int
}

func NewFooError(code int) error {
    err := &FooError{errors.NewErr("foo"), code}
    err.SetLocation(1)
    return err
}

func NewErrWithCause

func NewErrWithCause(other error, format string, args ...interface{}) Err

NewErrWithCause is used to return an Err with cause by other error for the purpose of embedding in other structures. The location is not specified, and needs to be set with a call to SetLocation.

For example:

type FooError struct {
    errors.Err
    code int
}

func (e *FooError) Annotate(format string, args ...interface{}) error {
    err := &FooError{errors.NewErrWithCause(e.Err, format, args...), e.code}
    err.SetLocation(1)
    return err
})

func (*Err) Cause

func (e *Err) Cause() error

The Cause of an error is the most recent error in the error stack that meets one of these criteria: the original error that was raised; the new error that was passed into the Wrap function; the most recently masked error; or nil if the error itself is considered the Cause. Normally this method is not invoked directly, but instead through the Cause stand alone function.

func (*Err) Error

func (e *Err) Error() string

Error implements error.Error.

func (*Err) Format

func (e *Err) Format(s fmt.State, verb rune)

Format implements fmt.Formatter When printing errors with %+v it also prints the stack trace. %#v unsurprisingly will print the real underlying type.

func (*Err) Location

func (e *Err) Location() (filename string, line int)

Location is the file and line of where the error was most recently created or annotated.

func (*Err) Message

func (e *Err) Message() string

Message returns the message stored with the most recent location. This is the empty string if the most recent call was Trace, or the message stored with Annotate or Mask.

func (*Err) SetLocation

func (e *Err) SetLocation(callDepth int)

SetLocation records the source location of the error at callDepth stack frames above the call.

func (*Err) StackTrace

func (e *Err) StackTrace() []string

StackTrace returns one string for each location recorded in the stack of errors. The first value is the originating error, with a line for each other annotation or tracing of the error.

func (*Err) Underlying

func (e *Err) Underlying() error

Underlying returns the previous error in the error stack, if any. A client should not ever really call this method. It is used to build the error stack and should not be introspected by client calls. Or more specifically, clients should not depend on anything but the Cause of an error.


Generated by godoc2md

More Repositories

1

ratelimit

Efficient token-bucket-based rate limiter package.
Go
2,679
star
2

juju

Orchestration engine that enables the deployment, integration and lifecycle management of applications at any scale, on any infrastructure (Kubernetes or otherwise).
Go
2,288
star
3

errgo

Error tracing and annotation.
Go
228
star
4

utils

General utility functions
Go
213
star
5

juju-gui

Juju-GUI is a web-based GUI for Juju <https://jujucharms.com/>.
JavaScript
182
star
6

loggo

A logging library for Go. Doesn't use the built in go log standard library, but instead offers a replacement.
Go
134
star
7

fslock

Go
129
star
8

persistent-cookiejar

cookiejar is a fork of net/http/cookiejar that allows serialisation of the stored cookies
Go
113
star
9

python-libjuju

Python library for the Juju API
Python
59
star
10

cheatsheet

A Juju Quicksheet with some common usage examples
58
star
11

charm-championship

Submissions for the Juju Charm Championship
43
star
12

charm-tools

Tools for charm authors and maintainers
Python
42
star
13

httprequest

JSON-oriented HTTP server and client helpers
Go
38
star
14

mutex

Provides a named machine level mutex shareable between processes.
Go
28
star
15

cmd

A command line implementation framework
Go
27
star
16

plugins

Basic collection of the first few plugins for Juju
Python
27
star
17

gomaasapi

Go bindings for talking to MAAS
Go
27
star
18

pubsub

Publish and subscribe functionality within a single process in Go.
Go
25
star
19

gnuflag

GNU-compatible flag handling with a stdlib-like API for Go
Go
25
star
20

docs

Juju documentation, edited on https://discourse.charmhub.io/, and published on https://juju.is/docs
Python
23
star
21

ansiterm

Colored writers and tabwriters.
Go
22
star
22

terraform-provider-juju

A Terraform provider for Juju
Go
21
star
23

gocharm

Write your charms in Go!
Go
21
star
24

layer-index

Index of layers for building charms
Python
21
star
25

testing

Testing gocheck suites and checkers used across juju projects
Go
19
star
26

retry

The retry package encapsulates the mechanism around retrying commands.
Go
19
star
27

charm-helpers

Python
18
star
28

amulet

Testing harness and tools for Juju Charms
Python
17
star
29

zaputil

Utility functions related to the zap logging package
Go
16
star
30

charmstore

The charm store server.
Go
15
star
31

clock

Clock definition and a testing clock.
Go
13
star
32

charm

Parsing and testing Juju charms
Go
13
star
33

xml

A fork of the Go xml package with fixed marshaling
Go
11
star
34

worker

Utilities for handling long lived Go workers
Go
10
star
35

juju-academy

Learn to use Juju
JavaScript
10
star
36

mgosession

Session pooling for the mgo package
Go
10
star
37

juju-crashdump

Script to assist in gathering logs and other debugging info from a Juju model
Python
10
star
38

charmstore-client

Client for charmstore.
Go
9
star
39

juju-talks

Presentations about Juju, pull requests welcome!
HTML
9
star
40

js-libjuju

JavaScript API client for Juju
TypeScript
9
star
41

replicaset

Create and manage mongodb replicasets.
Go
8
star
42

firestealer

A command line tool for parsing Prometheus metrics
Python
8
star
43

zip

Fork of Go's zip package with append feature.
Go
8
star
44

httpgovernor

HTTP request concurrency limiter
Go
7
star
45

packaging

An abstraction of different linux packaging systems.
Go
6
star
46

chaos-monkey

A tool to instrument chaos into a Juju environment.
Python
6
star
47

names

A package to deal with juju names (services, units, machines, etc)
Go
6
star
48

schema

coerce dynamically typed data structures into known forms.
Go
6
star
49

hello-juju-charm

The charm for the hello-juju application.
Python
5
star
50

jujusvg

Generate svgs from Juju bundles and environment.
Go
5
star
51

theblues

Python library for the juju charmstore (v4)
Python
5
star
52

1.25-upgrade

Tools to upgrade and move a 1.25 environment to a 2.2.4+ controller
Go
4
star
53

jenkins-github-lander

Web service to aid in landing approved branches automatically with a final test run through jenkins.
Python
4
star
54

juju-tosca

Juju Tosca Translator
Python
4
star
55

go-oracle-cloud

Go client interfacing with the oracle IAAS cloud API.
Go
4
star
56

mgo

The MongoDB driver for Go
Go
3
star
57

aclstore

A simple persistent store for ACLs, with HTTP API
Go
3
star
58

txjuju

A Twisted-based Juju client
Python
3
star
59

bakeryjs

Javascript implementation of the Macaroon Bakery
TypeScript
3
star
60

qthttptest

Check that JSON HTTP endpoints respond appropriately; compatible with quicktest.
Go
3
star
61

juju-restore

Restore script for Juju controllers
Go
3
star
62

version

Go
3
star
63

collections

Deque and set implementations
Go
3
star
64

bundlechanges

A Go library to generate the list of changes required to deploy a bundle
Go
3
star
65

postgrestest

Go support for testing against a live Postgres database
Go
2
star
66

concurrency-limiter

Limit the number of asynchronous concurrent tasks running
JavaScript
2
star
67

juju-gui-charm

Charm for Juju GUI.
Python
2
star
68

autopilot-log-collector

Python
2
star
69

mgopurge

A tool to repair broken mgo/txn transaction references in a Juju MongoDB instance.
Go
2
star
70

httpprof

httpprof is a fork of net/http/pprof which works correctly when not at the server's root
Go
2
star
71

hello-juju

A simple application used to demonstrate juju relations.
HTML
2
star
72

blobstore

This package provides a Mongo GridFS-backed blob storage engine.
Go
2
star
73

mgoutil

A Go package holding utilities related to the mgo package
Go
2
star
74

lru

A Go implementation of a least-recently-used cache
Go
2
star
75

description

Describes the Juju 2.x and 3.x serialization format of a model
Go
2
star
76

charmrepo

Charm repositories and charmstore client packages
Go
2
star
77

webbrowser

Go helpers for interacting with Web browsers.
Go
2
star
78

fake-juju

A juju binary using the dummy provider for integration test purposes.
Go
2
star
79

juju-qa-jenkins

Jenkins configuration for Juju CI
Python
2
star
80

termserver

LXD image builder for the jujushell service
Makefile
1
star
81

rfc

Go implementations of various standards, particularly IETF RFCs.
Go
1
star
82

juju-bundlelib

A Python library for working with Juju bundles.
Python
1
star
83

idmclient

client for USSO to macaroons bridge server
Go
1
star
84

mgomonitor

prometheus stats for gopkg.in/mgo.v2
Go
1
star
85

jknife

jknife are juju db surgery tools - this should only be used with direction of a Juju engineer
Go
1
star
86

jasp

CSS
1
star
87

jujuapidoc

Generate information on the Juju API
Go
1
star
88

juju-controller

A Juju controller charm
Python
1
star
89

jaaslibjs

JavaScript library for interacting with the JAAS services
JavaScript
1
star
90

http

Juju wrapper for the standard go HTTP library.
Go
1
star
91

naturalsort

Sort strings according to natural sort order.
Go
1
star
92

charm-developer-docs

Documenting how to write a Juju charm
Shell
1
star
93

lxc

Fork of lxd/lxc to add Juju specific tweaks
Go
1
star
94

romulus

Go
1
star
95

usso

Go
1
star
96

juju-process-docker

a plugin to allow juju to interface with docker
Go
1
star
97

charm-base-images

Shell
1
star
98

proxy

A golang type for grouping information about proxy variables.
Go
1
star
99

jaas-monitor

Monitor all your jaas models (prototype)
Shell
1
star
100

os

Host OS and series abstractions for Go.
Go
1
star