errors

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2017 License: BSD-2-Clause Imports: 6 Imported by: 370

README

errors

Package errors provides simple error handling primitives and behavioral errors.

go get github.com/corestoreio/errors

Read the package documentation for more information.

Contributing

We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high.

Before proposing a change, please discuss your change by raising an issue.

Licence

BSD-2-Clause

Copyright (c) 2015, Dave Cheney <[email protected]>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Licensing

CoreStore is licensed under the Apache License, Version 2.0. See LICENSE for the full license text.

Copyright 2015-2017, Cyrill @ Schumacher.fm and the CoreStore contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Documentation

Overview

Package errors provides simple error handling primitives and behavioral errors.

Hello there! Read the presentation http://dave.cheney.net/paste/gocon-spring-2016.pdf to see what the big deal is.

http://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully

Read this for asserting errors for their behaviour http://dave.cheney.net/2014/12/24/inspecting-errors

The traditional error handling idiom in Go is roughly akin to

if err != nil {
        return err
}

which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error.

Adding context to an error

The errors.Wrap function returns a new error that adds context to the original error by recording a stack trace at the point Wrap is called, and the supplied message. For example

_, err := ioutil.ReadAll(r)
if err != nil {
        return errors.Wrap(err, "read failed")
}

If additional control is required the errors.WithStack and errors.WithMessage functions destructure errors.Wrap into its component operations of annotating an error with a stack trace and an a message, respectively.

Retrieving the cause of an error

Using errors.Wrap constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface

type causer interface {
        Cause() error
}

can be inspected by errors.Cause. errors.Cause will recursively retrieve the topmost error which does not implement causer, which is assumed to be the original cause. For example:

switch err := errors.Cause(err).(type) {
case *MyError:
        // handle specifically
default:
        // unknown error
}

causer interface is not exported by this package, but is considered a part of stable public API.

Formatted printing of errors

All error values returned from this package implement fmt.Formatter and can be formatted by the fmt package. The following verbs are supported

%s    print the error. If the error has a Cause it will be
      printed recursively
%v    see %s
%+v   extended format. Each Frame of the error's StackTrace will
      be printed in detail.

Retrieving the stack trace of an error or wrapper

New, Errorf, Wrap, and Wrapf record a stack trace at the point they are invoked. This information can be retrieved with the following interface.

type stackTracer interface {
        StackTrace() errors.StackTrace
}

Where errors.StackTrace is defined as

type StackTrace []Frame

The Frame type represents a call site in the stack trace. Frame supports the fmt.Formatter interface that can be used for printing information about the stack trace of this error. For example:

if err, ok := err.(stackTracer); ok {
        for _, f := range err.StackTrace() {
                fmt.Printf("%+s:%d", f)
        }
}

stackTracer interface is not exported by this package, but is considered a part of stable public API.

See the documentation for Frame.Format for more details.

Example (StackTrace)
package main

import (
	"fmt"

	"github.com/pkg/errors"
)

func fn() error {
	e1 := errors.New("error")
	e2 := errors.Wrap(e1, "inner")
	e3 := errors.Wrap(e2, "middle")
	return errors.Wrap(e3, "outer")
}

func main() {
	type stackTracer interface {
		StackTrace() errors.StackTrace
	}

	err, ok := errors.Cause(fn()).(stackTracer)
	if !ok {
		panic("oops, err does not implement stackTracer")
	}

	st := err.StackTrace()
	fmt.Printf("%+v", st[0:2]) // top two frames

	// Example output:
	// github.com/pkg/errors_test.fn
	//	/home/dfc/src/github.com/pkg/errors/example_test.go:47
	// github.com/pkg/errors_test.Example_stackTrace
	//	/home/dfc/src/github.com/pkg/errors/example_test.go:127
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cause

func Cause(err error) error

Cause returns the underlying cause of the error, if possible. An error value has a cause if it implements the following interface:

type causer interface {
       Cause() error
}

If the error does not implement Cause, the original error will be returned. If the error is nil, nil will be returned without further investigation.

Example
package main

import (
	"fmt"

	"github.com/pkg/errors"
)

func fn() error {
	e1 := errors.New("error")
	e2 := errors.Wrap(e1, "inner")
	e3 := errors.Wrap(e2, "middle")
	return errors.Wrap(e3, "outer")
}

func main() {
	err := fn()
	fmt.Println(err)
	fmt.Println(errors.Cause(err))

}
Output:

outer: middle: inner: error
error
Example (Printf)
package main

import (
	"fmt"

	"github.com/pkg/errors"
)

func main() {
	err := errors.Wrap(func() error {
		return func() error {
			return errors.Errorf("hello %s", fmt.Sprintf("world"))
		}()
	}(), "failed")

	fmt.Printf("%v", err)

}
Output:

failed: hello world

func CausedBehaviour

func CausedBehaviour(err error, bhf BehaviourFunc) bool

CausedBehaviour returns the first underlying caused behaviour of the error, if possible. An error value has a cause if it implements the following interface:

type Causer interface {
       Cause() error
}

If the error does not implement Cause or is nil, false will be returned. The variable bhf gets called on each unwrapped "cause" error

func Errorf

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

Errorf formats according to a format specifier and returns the string as a value that satisfies error. Errorf also records the stack trace at the point it was called.

Example (Extended)
package main

import (
	"fmt"

	"github.com/pkg/errors"
)

func main() {
	err := errors.Errorf("whoops: %s", "foo")
	fmt.Printf("%+v", err)

	// Example output:
	// whoops: foo
	// github.com/pkg/errors_test.ExampleErrorf
	//         /home/dfc/src/github.com/pkg/errors/example_test.go:101
	// testing.runExample
	//         /home/dfc/go/src/testing/example.go:114
	// testing.RunExamples
	//         /home/dfc/go/src/testing/example.go:38
	// testing.(*M).Run
	//         /home/dfc/go/src/testing/testing.go:744
	// main.main
	//         /github.com/pkg/errors/_test/_testmain.go:102
	// runtime.main
	//         /home/dfc/go/src/runtime/proc.go:183
	// runtime.goexit
	//         /home/dfc/go/src/runtime/asm_amd64.s:2059
}

func FormatLineFunc

func FormatLineFunc(errs []error) string

FormatLineFunc is a basic formatter that outputs the errors that occurred along with the filename and the line number of the errors. Only if the error has a Location() function.

func HasBehaviour

func HasBehaviour(err error, bfs ...BehaviourFunc) bool

HasBehaviour checks if err contains at least one of the provided behaviour functions. Does not traverse recursive into the error.

func IsAborted

func IsAborted(err error) bool

IsAborted reports whether err was created with NewAborted() or implements interface:

type Aborteder interface {
       Aborted() bool
}

func IsAlreadyCaptured

func IsAlreadyCaptured(err error) bool

IsAlreadyCaptured reports whether err was created with NewAlreadyCaptured() or implements interface:

type AlreadyCaptureder interface {
       AlreadyCaptured() bool
}

func IsAlreadyClosed

func IsAlreadyClosed(err error) bool

IsAlreadyClosed reports whether err was created with NewAlreadyClosed() or implements interface:

type AlreadyCloseder interface {
       AlreadyClosed() bool
}

func IsAlreadyExists

func IsAlreadyExists(err error) bool

IsAlreadyExists reports whether err was created with NewAlreadyExists() or implements interface:

type AlreadyExistser interface {
       AlreadyExists() bool
}

func IsAlreadyInUse

func IsAlreadyInUse(err error) bool

IsAlreadyInUse reports whether err was created with NewAlreadyInUse() or implements interface:

type AlreadyInUseer interface {
       AlreadyInUse() bool
}

func IsAlreadyRefunded

func IsAlreadyRefunded(err error) bool

IsAlreadyRefunded reports whether err was created with NewAlreadyRefunded() or implements interface:

type AlreadyRefundeder interface {
       AlreadyRefunded() bool
}

func IsBlocked

func IsBlocked(err error) bool

IsBlocked reports whether err was created with NewBlocked() or implements interface:

type Blockeder interface {
       Blocked() bool
}

func IsConnectionFailed

func IsConnectionFailed(err error) bool

IsConnectionFailed reports whether err was created with NewConnectionFailed() or implements interface:

type ConnectionFaileder interface {
       ConnectionFailed() bool
}

func IsDeclined

func IsDeclined(err error) bool

IsDeclined reports whether err was created with NewDeclined() or implements interface:

type Declineder interface {
       Declined() bool
}

func IsDenied

func IsDenied(err error) bool

IsDenied reports whether err was created with NewDenied() or implements interface:

type Denieder interface {
       Denied() bool
}

func IsDuplicated

func IsDuplicated(err error) bool

IsDuplicated reports whether err was created with NewDuplicated() or implements interface:

type Duplicateder interface {
       Duplicated() bool
}

func IsEmpty

func IsEmpty(err error) bool

IsEmpty reports whether err was created with NewEmpty() or implements interface:

type Emptyer interface {
       Empty() bool
}

func IsExceeded

func IsExceeded(err error) bool

IsExceeded reports whether err was created with NewExceeded() or implements interface:

type Exceededer interface {
       Exceeded() bool
}

func IsExpired

func IsExpired(err error) bool

IsExpired reports whether err was created with NewExpired() or implements interface:

type Expireder interface {
       Expired() bool
}

func IsFatal

func IsFatal(err error) bool

IsFatal reports whether err was created with NewFatal() or implements interface:

type Fataler interface {
       Fatal() bool
}

func IsInProgress

func IsInProgress(err error) bool

IsInProgress reports whether err was created with NewInProgress() or implements interface:

type InProgresser interface {
       InProgress() bool
}

func IsInsufficient

func IsInsufficient(err error) bool

IsInsufficient reports whether err was created with NewInsufficient() or implements interface:

type Insufficienter interface {
       Insufficient() bool
}

func IsInterrupted

func IsInterrupted(err error) bool

IsInterrupted reports whether err was created with NewInterrupted() or implements interface:

type Interrupteder interface {
       Interrupted() bool
}

func IsLocked

func IsLocked(err error) bool

IsLocked reports whether err was created with NewLocked() or implements interface:

type Lockeder interface {
       Locked() bool
}

func IsMismatch

func IsMismatch(err error) bool

IsMismatch reports whether err was created with NewMismatch() or implements interface:

type Mismatcher interface {
       Mismatch() bool
}

func IsNotAcceptable

func IsNotAcceptable(err error) bool

IsNotAcceptable reports whether err was created with NewNotAcceptable() or implements interface:

type NotAcceptableer interface {
       NotAcceptable() bool
}

func IsNotAllowed

func IsNotAllowed(err error) bool

IsNotAllowed reports whether err was created with NewNotAllowed() or implements interface:

type NotAlloweder interface {
       NotAllowed() bool
}

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err was created with NewNotFound() or implements interface:

type NotFounder interface {
       NotFound() bool
}

func IsNotImplemented

func IsNotImplemented(err error) bool

IsNotImplemented reports whether err was created with NewNotImplemented() or implements interface:

type NotImplementeder interface {
       NotImplemented() bool
}

func IsNotRecoverable

func IsNotRecoverable(err error) bool

IsNotRecoverable reports whether err was created with NewNotRecoverable() or implements interface:

type NotRecoverableer interface {
       NotRecoverable() bool
}

func IsNotSupported

func IsNotSupported(err error) bool

IsNotSupported reports whether err was created with NewNotSupported() or implements interface:

type NotSupporteder interface {
       NotSupported() bool
}

func IsNotValid

func IsNotValid(err error) bool

IsNotValid reports whether err was created with NewNotValid() or implements interface:

type NotValider interface {
       NotValid() bool
}

func IsOverflowed

func IsOverflowed(err error) bool

IsOverflowed reports whether err was created with NewOverflowed() or implements interface:

type Overfloweder interface {
       Overflowed() bool
}

func IsPermissionDenied

func IsPermissionDenied(err error) bool

IsPermissionDenied reports whether err was created with NewPermissionDenied() or implements interface:

type PermissionDenieder interface {
       PermissionDenied() bool
}

func IsQuotaExceeded

func IsQuotaExceeded(err error) bool

IsQuotaExceeded reports whether err was created with NewQuotaExceeded() or implements interface:

type QuotaExceededer interface {
       QuotaExceeded() bool
}

func IsReadFailed

func IsReadFailed(err error) bool

IsReadFailed reports whether err was created with NewReadFailed() or implements interface:

type ReadFaileder interface {
       ReadFailed() bool
}

func IsRejected

func IsRejected(err error) bool

IsRejected reports whether err was created with NewRejected() or implements interface:

type Rejecteder interface {
       Rejected() bool
}

func IsRequired

func IsRequired(err error) bool

IsRequired reports whether err was created with NewRequired() or implements interface:

type Requireder interface {
       Required() bool
}

func IsRestricted

func IsRestricted(err error) bool

IsRestricted reports whether err was created with NewRestricted() or implements interface:

type Restricteder interface {
       Restricted() bool
}

func IsRevoked

func IsRevoked(err error) bool

IsRevoked reports whether err was created with NewRevoked() or implements interface:

type Revokeder interface {
       Revoked() bool
}

func IsTemporary

func IsTemporary(err error) bool

IsTemporary reports whether err was created with NewTemporary() or implements interface:

type Temporaryer interface {
       Temporary() bool
}

func IsTerminated

func IsTerminated(err error) bool

IsTerminated reports whether err was created with NewTerminated() or implements interface:

type Terminateder interface {
       Terminated() bool
}

func IsTimeout

func IsTimeout(err error) bool

IsTimeout reports whether err was created with NewTimeout() or implements interface:

type Timeouter interface {
       Timeout() bool
}

func IsTooLarge

func IsTooLarge(err error) bool

IsTooLarge reports whether err was created with NewTooLarge() or implements interface:

type TooLargeer interface {
       TooLarge() bool
}

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized reports whether err was created with NewUnauthorized() or implements interface:

type Unauthorizeder interface {
       Unauthorized() bool
}

func IsUnavailable

func IsUnavailable(err error) bool

IsUnavailable reports whether err was created with NewUnavailable() or implements interface:

type Unavailableer interface {
       Unavailable() bool
}

func IsUserNotFound

func IsUserNotFound(err error) bool

IsUserNotFound reports whether err was created with NewUserNotFound() or implements interface:

type UserNotFounder interface {
       UserNotFound() bool
}

func IsVerificationFailed

func IsVerificationFailed(err error) bool

IsVerificationFailed reports whether err was created with NewVerificationFailed() or implements interface:

type VerificationFaileder interface {
       VerificationFailed() bool
}

func IsWriteFailed

func IsWriteFailed(err error) bool

IsWriteFailed reports whether err was created with NewWriteFailed() or implements interface:

type WriteFaileder interface {
       WriteFailed() bool
}

func IsWrongVersion

func IsWrongVersion(err error) bool

IsWrongVersion reports whether err was created with NewWrongVersion() or implements interface:

type WrongVersioner interface {
       WrongVersion() bool
}

func MultiErrContainsAll

func MultiErrContainsAll(err error, bfs ...BehaviourFunc) bool

MultiErrContainsAll checks if err contains a behavioral error. 1st argument err must be of type (*MultiErr) and validate function vf at least one of the many Is*() e.g. IsNotValid(), see type BehaviourFunc. All validate functions must return true. If there are multiple behavioral errors and one BehaviourFunc it will stop after all errors matches the BehaviourFunc, not at the first match.

func MultiErrContainsAny

func MultiErrContainsAny(err error, bfs ...BehaviourFunc) bool

MultiErrContainsAny checks if err contains at least one behavioral error. 1st argument err must be of type (*MultiErr) and validate function vf at least one of the many Is*() e.g. IsNotValid(), see type BehaviourFunc.

func New

func New(message string) error

New returns an error with the supplied message. New also records the stack trace at the point it was called.

Example
package main

import (
	"fmt"

	"github.com/pkg/errors"
)

func main() {
	err := errors.New("whoops")
	fmt.Println(err)

}
Output:

whoops
Example (Printf)
package main

import (
	"fmt"

	"github.com/pkg/errors"
)

func main() {
	err := errors.New("whoops")
	fmt.Printf("%+v", err)

	// Example output:
	// whoops
	// github.com/pkg/errors_test.ExampleNew_printf
	//         /home/dfc/src/github.com/pkg/errors/example_test.go:17
	// testing.runExample
	//         /home/dfc/go/src/testing/example.go:114
	// testing.RunExamples
	//         /home/dfc/go/src/testing/example.go:38
	// testing.(*M).Run
	//         /home/dfc/go/src/testing/testing.go:744
	// main.main
	//         /github.com/pkg/errors/_test/_testmain.go:106
	// runtime.main
	//         /home/dfc/go/src/runtime/proc.go:183
	// runtime.goexit
	//         /home/dfc/go/src/runtime/asm_amd64.s:2059
}

func NewAborted

func NewAborted(err error, msg string, args ...interface{}) error

NewAborted returns an error which wraps err that satisfies IsAborted().

func NewAbortedf

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

NewAbortedf returns a formatted error that satisfies IsAborted().

func NewAlreadyCaptured

func NewAlreadyCaptured(err error, msg string, args ...interface{}) error

NewAlreadyCaptured returns an error which wraps err that satisfies IsAlreadyCaptured().

func NewAlreadyCapturedf

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

NewAlreadyCapturedf returns a formatted error that satisfies IsAlreadyCaptured().

func NewAlreadyClosed

func NewAlreadyClosed(err error, msg string, args ...interface{}) error

NewAlreadyClosed returns an error which wraps err that satisfies IsAlreadyClosed().

func NewAlreadyClosedf

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

NewAlreadyClosedf returns a formatted error that satisfies IsAlreadyClosed().

func NewAlreadyExists

func NewAlreadyExists(err error, msg string, args ...interface{}) error

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

func NewAlreadyExistsf

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

NewAlreadyExistsf returns a formatted error that satisfies IsAlreadyExists().

func NewAlreadyInUse

func NewAlreadyInUse(err error, msg string, args ...interface{}) error

NewAlreadyInUse returns an error which wraps err that satisfies IsAlreadyInUse().

func NewAlreadyInUsef

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

NewAlreadyInUsef returns a formatted error that satisfies IsAlreadyInUse().

func NewAlreadyRefunded

func NewAlreadyRefunded(err error, msg string, args ...interface{}) error

NewAlreadyRefunded returns an error which wraps err that satisfies IsAlreadyRefunded().

func NewAlreadyRefundedf

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

NewAlreadyRefundedf returns a formatted error that satisfies IsAlreadyRefunded().

func NewBlocked

func NewBlocked(err error, msg string, args ...interface{}) error

NewBlocked returns an error which wraps err that satisfies IsBlocked().

func NewBlockedf

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

NewBlockedf returns a formatted error that satisfies IsBlocked().

func NewConnectionFailed

func NewConnectionFailed(err error, msg string, args ...interface{}) error

NewConnectionFailed returns an error which wraps err that satisfies IsConnectionFailed().

func NewConnectionFailedf

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

NewConnectionFailedf returns a formatted error that satisfies IsConnectionFailed().

func NewDeclined

func NewDeclined(err error, msg string, args ...interface{}) error

NewDeclined returns an error which wraps err that satisfies IsDeclined().

func NewDeclinedf

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

NewDeclinedf returns a formatted error that satisfies IsDeclined().

func NewDenied

func NewDenied(err error, msg string, args ...interface{}) error

NewDenied returns an error which wraps err that satisfies IsDenied().

func NewDeniedf

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

NewDeniedf returns a formatted error that satisfies IsDenied().

func NewDuplicated

func NewDuplicated(err error, msg string, args ...interface{}) error

NewDuplicated returns an error which wraps err that satisfies IsDuplicated().

func NewDuplicatedf

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

NewDuplicatedf returns a formatted error that satisfies IsDuplicated().

func NewEmpty

func NewEmpty(err error, msg string, args ...interface{}) error

NewEmpty returns an error which wraps err that satisfies IsEmpty().

func NewEmptyf

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

NewEmptyf returns a formatted error that satisfies IsEmpty().

func NewExceeded

func NewExceeded(err error, msg string, args ...interface{}) error

NewExceeded returns an error which wraps err that satisfies IsExceeded().

func NewExceededf

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

NewExceededf returns a formatted error that satisfies IsExceeded().

func NewExpired

func NewExpired(err error, msg string, args ...interface{}) error

NewExpired returns an error which wraps err that satisfies IsExpired().

func NewExpiredf

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

NewExpiredf returns a formatted error that satisfies IsExpired().

func NewFatal

func NewFatal(err error, msg string, args ...interface{}) error

NewFatal returns an error which wraps err that satisfies IsFatal().

func NewFatalf

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

NewFatalf returns a formatted error that satisfies IsFatal().

func NewInProgress

func NewInProgress(err error, msg string, args ...interface{}) error

NewInProgress returns an error which wraps err that satisfies IsInProgress().

func NewInProgressf

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

NewInProgressf returns a formatted error that satisfies IsInProgress().

func NewInsufficient

func NewInsufficient(err error, msg string, args ...interface{}) error

NewInsufficient returns an error which wraps err that satisfies IsInsufficient().

func NewInsufficientf

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

NewInsufficientf returns a formatted error that satisfies IsInsufficient().

func NewInterrupted

func NewInterrupted(err error, msg string, args ...interface{}) error

NewInterrupted returns an error which wraps err that satisfies IsInterrupted().

func NewInterruptedf

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

NewInterruptedf returns a formatted error that satisfies IsInterrupted().

func NewLocked

func NewLocked(err error, msg string, args ...interface{}) error

NewLocked returns an error which wraps err that satisfies IsLocked().

func NewLockedf

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

NewLockedf returns a formatted error that satisfies IsLocked().

func NewMismatch

func NewMismatch(err error, msg string, args ...interface{}) error

NewMismatch returns an error which wraps err that satisfies IsMismatch().

func NewMismatchf

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

NewMismatchf returns a formatted error that satisfies IsMismatch().

func NewNotAcceptable

func NewNotAcceptable(err error, msg string, args ...interface{}) error

NewNotAcceptable returns an error which wraps err that satisfies IsNotAcceptable().

func NewNotAcceptablef

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

NewNotAcceptablef returns a formatted error that satisfies IsNotAcceptable().

func NewNotAllowed

func NewNotAllowed(err error, msg string, args ...interface{}) error

NewNotAllowed returns an error which wraps err that satisfies IsNotAllowed().

func NewNotAllowedf

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

NewNotAllowedf returns a formatted error that satisfies IsNotAllowed().

func NewNotFound

func NewNotFound(err error, msg string, args ...interface{}) error

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

func NewNotFoundf

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

NewNotFoundf returns a formatted error that satisfies IsNotFound().

func NewNotImplemented

func NewNotImplemented(err error, msg string, args ...interface{}) error

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

func NewNotImplementedf

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

NewNotImplementedf returns a formatted error that satisfies IsNotImplemented().

func NewNotRecoverable

func NewNotRecoverable(err error, msg string, args ...interface{}) error

NewNotRecoverable returns an error which wraps err that satisfies IsNotRecoverable().

func NewNotRecoverablef

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

NewNotRecoverablef returns a formatted error that satisfies IsNotRecoverable().

func NewNotSupported

func NewNotSupported(err error, msg string, args ...interface{}) error

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

func NewNotSupportedf

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

NewNotSupportedf returns a formatted error that satisfies IsNotSupported().

func NewNotValid

func NewNotValid(err error, msg string, args ...interface{}) error

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

func NewNotValidf

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

NewNotValidf returns a formatted error that satisfies IsNotValid().

func NewOverflowed

func NewOverflowed(err error, msg string, args ...interface{}) error

NewOverflowed returns an error which wraps err that satisfies IsOverflowed().

func NewOverflowedf

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

NewOverflowedf returns a formatted error that satisfies IsOverflowed().

func NewPermissionDenied

func NewPermissionDenied(err error, msg string, args ...interface{}) error

NewPermissionDenied returns an error which wraps err that satisfies IsPermissionDenied().

func NewPermissionDeniedf

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

NewPermissionDeniedf returns a formatted error that satisfies IsPermissionDenied().

func NewQuotaExceeded

func NewQuotaExceeded(err error, msg string, args ...interface{}) error

NewQuotaExceeded returns an error which wraps err that satisfies IsQuotaExceeded().

func NewQuotaExceededf

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

NewQuotaExceededf returns a formatted error that satisfies IsQuotaExceeded().

func NewReadFailed

func NewReadFailed(err error, msg string, args ...interface{}) error

NewReadFailed returns an error which wraps err that satisfies IsReadFailed().

func NewReadFailedf

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

NewReadFailedf returns a formatted error that satisfies IsReadFailed().

func NewRejected

func NewRejected(err error, msg string, args ...interface{}) error

NewRejected returns an error which wraps err that satisfies IsRejected().

func NewRejectedf

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

NewRejectedf returns a formatted error that satisfies IsRejected().

func NewRequired

func NewRequired(err error, msg string, args ...interface{}) error

NewRequired returns an error which wraps err that satisfies IsRequired().

func NewRequiredf

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

NewRequiredf returns a formatted error that satisfies IsRequired().

func NewRestricted

func NewRestricted(err error, msg string, args ...interface{}) error

NewRestricted returns an error which wraps err that satisfies IsRestricted().

func NewRestrictedf

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

NewRestrictedf returns a formatted error that satisfies IsRestricted().

func NewRevoked

func NewRevoked(err error, msg string, args ...interface{}) error

NewRevoked returns an error which wraps err that satisfies IsRevoked().

func NewRevokedf

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

NewRevokedf returns a formatted error that satisfies IsRevoked().

func NewTemporary

func NewTemporary(err error, msg string, args ...interface{}) error

NewTemporary returns an error which wraps err that satisfies IsTemporary().

func NewTemporaryf

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

NewTemporaryf returns a formatted error that satisfies IsTemporary().

func NewTerminated

func NewTerminated(err error, msg string, args ...interface{}) error

NewTerminated returns an error which wraps err that satisfies IsTerminated().

func NewTerminatedf

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

NewTerminatedf returns a formatted error that satisfies IsTerminated().

func NewTimeout

func NewTimeout(err error, msg string, args ...interface{}) error

NewTimeout returns an error which wraps err that satisfies IsTimeout().

func NewTimeoutf

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

NewTimeoutf returns a formatted error that satisfies IsTimeout().

func NewTooLarge

func NewTooLarge(err error, msg string, args ...interface{}) error

NewTooLarge returns an error which wraps err that satisfies IsTooLarge().

func NewTooLargef

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

NewTooLargef returns a formatted error that satisfies IsTooLarge().

func NewUnauthorized

func NewUnauthorized(err error, msg string, args ...interface{}) error

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

func NewUnauthorizedf

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

NewUnauthorizedf returns a formatted error that satisfies IsUnauthorized().

func NewUnavailable

func NewUnavailable(err error, msg string, args ...interface{}) error

NewUnavailable returns an error which wraps err that satisfies IsUnavailable().

func NewUnavailablef

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

NewUnavailablef returns a formatted error that satisfies IsUnavailable().

func NewUserNotFound

func NewUserNotFound(err error, msg string, args ...interface{}) error

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

func NewUserNotFoundf

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

NewUserNotFoundf returns a formatted error that satisfies IsUserNotFound().

func NewVerificationFailed

func NewVerificationFailed(err error, msg string, args ...interface{}) error

NewVerificationFailed returns an error which wraps err that satisfies IsVerificationFailed().

func NewVerificationFailedf

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

NewVerificationFailedf returns a formatted error that satisfies IsVerificationFailed().

func NewWriteFailed

func NewWriteFailed(err error, msg string, args ...interface{}) error

NewWriteFailed returns an error which wraps err that satisfies IsWriteFailed().

func NewWriteFailedf

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

NewWriteFailedf returns a formatted error that satisfies IsWriteFailed().

func NewWrongVersion

func NewWrongVersion(err error, msg string, args ...interface{}) error

NewWrongVersion returns an error which wraps err that satisfies IsWrongVersion().

func NewWrongVersionf

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

NewWrongVersionf returns a formatted error that satisfies IsWrongVersion().

func WithMessage

func WithMessage(err error, message string) error

WithMessage annotates err with a new message. If err is nil, WithMessage returns nil.

Example
package main

import (
	"fmt"

	"github.com/pkg/errors"
)

func main() {
	cause := errors.New("whoops")
	err := errors.WithMessage(cause, "oh noes")
	fmt.Println(err)

}
Output:

oh noes: whoops

func WithStack

func WithStack(err error) error

WithStack annotates err with a stack trace at the point WithStack was called. If err is nil, WithStack returns nil.

Example
package main

import (
	"fmt"

	"github.com/pkg/errors"
)

func main() {
	cause := errors.New("whoops")
	err := errors.WithStack(cause)
	fmt.Println(err)

}
Output:

whoops
Example (Printf)
package main

import (
	"fmt"

	"github.com/pkg/errors"
)

func main() {
	cause := errors.New("whoops")
	err := errors.WithStack(cause)
	fmt.Printf("%+v", err)

	// Example Output:
	// whoops
	// github.com/pkg/errors_test.ExampleWithStack_printf
	//         /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55
	// testing.runExample
	//         /usr/lib/go/src/testing/example.go:114
	// testing.RunExamples
	//         /usr/lib/go/src/testing/example.go:38
	// testing.(*M).Run
	//         /usr/lib/go/src/testing/testing.go:744
	// main.main
	//         github.com/pkg/errors/_test/_testmain.go:106
	// runtime.main
	//         /usr/lib/go/src/runtime/proc.go:183
	// runtime.goexit
	//         /usr/lib/go/src/runtime/asm_amd64.s:2086
	// github.com/pkg/errors_test.ExampleWithStack_printf
	//         /home/fabstu/go/src/github.com/pkg/errors/example_test.go:56
	// testing.runExample
	//         /usr/lib/go/src/testing/example.go:114
	// testing.RunExamples
	//         /usr/lib/go/src/testing/example.go:38
	// testing.(*M).Run
	//         /usr/lib/go/src/testing/testing.go:744
	// main.main
	//         github.com/pkg/errors/_test/_testmain.go:106
	// runtime.main
	//         /usr/lib/go/src/runtime/proc.go:183
	// runtime.goexit
	//         /usr/lib/go/src/runtime/asm_amd64.s:2086
}

func Wrap

func Wrap(err error, message string) error

Wrap returns an error annotating err with a stack trace at the point Wrap is called, and the supplied message. If err is nil, Wrap returns nil.

Example
package main

import (
	"fmt"

	"github.com/pkg/errors"
)

func main() {
	cause := errors.New("whoops")
	err := errors.Wrap(cause, "oh noes")
	fmt.Println(err)

}
Output:

oh noes: whoops
Example (Extended)
package main

import (
	"fmt"

	"github.com/pkg/errors"
)

func fn() error {
	e1 := errors.New("error")
	e2 := errors.Wrap(e1, "inner")
	e3 := errors.Wrap(e2, "middle")
	return errors.Wrap(e3, "outer")
}

func main() {
	err := fn()
	fmt.Printf("%+v\n", err)

	// Example output:
	// error
	// github.com/pkg/errors_test.fn
	//         /home/dfc/src/github.com/pkg/errors/example_test.go:47
	// github.com/pkg/errors_test.ExampleCause_printf
	//         /home/dfc/src/github.com/pkg/errors/example_test.go:63
	// testing.runExample
	//         /home/dfc/go/src/testing/example.go:114
	// testing.RunExamples
	//         /home/dfc/go/src/testing/example.go:38
	// testing.(*M).Run
	//         /home/dfc/go/src/testing/testing.go:744
	// main.main
	//         /github.com/pkg/errors/_test/_testmain.go:104
	// runtime.main
	//         /home/dfc/go/src/runtime/proc.go:183
	// runtime.goexit
	//         /home/dfc/go/src/runtime/asm_amd64.s:2059
	// github.com/pkg/errors_test.fn
	// 	  /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner
	// github.com/pkg/errors_test.fn
	//        /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle
	// github.com/pkg/errors_test.fn
	//      /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer
}

func Wrapf

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

Wrapf returns an error annotating err with a stack trace at the point Wrapf is call, and the format specifier. If err is nil, Wrapf returns nil.

Example
package main

import (
	"fmt"

	"github.com/pkg/errors"
)

func main() {
	cause := errors.New("whoops")
	err := errors.Wrapf(cause, "oh noes #%d", 2)
	fmt.Println(err)

}
Output:

oh noes #2: whoops

Types

type BehaviourFunc

type BehaviourFunc func(error) bool

BehaviourFunc defines the signature needed for a function to check if an error has a specific behaviour attached.

type Error

type Error string

Error type can be used for constant errors and says nothing about its behaviour. http://dave.cheney.net/2016/04/07/constant-errors

func (Error) Error

func (e Error) Error() string

Error implements the error interface

type ErrorFormatFunc

type ErrorFormatFunc func([]error) string

ErrorFormatFunc is a function callback that is called by Error to turn the list of errors into a string.

type Frame

type Frame uintptr

Frame represents a program counter inside a stack frame.

func (Frame) Format

func (f Frame) Format(s fmt.State, verb rune)

Format formats the frame according to the fmt.Formatter interface.

%s    source file
%d    source line
%n    function name
%v    equivalent to %s:%d

Format accepts flags that alter the printing of some verbs, as follows:

%+s   path of source file relative to the compile time GOPATH
%+v   equivalent to %+s:%d

type MultiErr

type MultiErr struct {
	Errors    []error
	Formatter ErrorFormatFunc
}

MultiErr represents a container for collecting and printing multiple errors.

func NewMultiErr

func NewMultiErr(errs ...error) *MultiErr

NewMultiErr creates a new multi error struct.

func (*MultiErr) AppendErrors

func (m *MultiErr) AppendErrors(errs ...error) *MultiErr

AppendErrors adds multiple errors to the container. Does not add a location. If *MultiErr is nil it creates a new pointer and returns it.

func (*MultiErr) Error

func (m *MultiErr) Error() string

Error returns a string where each error has been separated by a line break. The location will be added to the output to show you the file name and line number.

func (*MultiErr) HasErrors

func (m *MultiErr) HasErrors() bool

HasErrors checks if Multi contains errors.

type StackTrace

type StackTrace []Frame

StackTrace is stack of Frames from innermost (newest) to outermost (oldest).

func (StackTrace) Format

func (st StackTrace) Format(s fmt.State, verb rune)

Format formats the stack of Frames according to the fmt.Formatter interface.

%s	lists source files for each Frame in the stack
%v	lists the source file and line number for each Frame in the stack

Format accepts flags that alter the printing of some verbs, as follows:

%+v   Prints filename, function, and line number for each Frame in the stack.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL