Simple error handling primitives


errors Travis-CI AppVeyor GoDoc Report card Sourcegraph

Package errors provides simple error handling primitives.

go get

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. For example

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

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 can be inspected by errors.Cause.

type causer interface {
        Cause() error

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
        // unknown error

Read the package documentation for more information.


With the upcoming Go2 error proposals this package is moving into maintenance mode. The roadmap for a 1.0 release is as follows:

  • 0.9. Remove pre Go 1.9 and Go 1.10 support, address outstanding pull requests (if possible)
  • 1.0. Final release.


Because of the Go2 errors changes, this package is not accepting proposals for new functionality. With that said, we welcome pull requests, bug fixes and issue reports.

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



  • Create some form of MultiError type

    Create some form of MultiError type

    Note: the scope of this issue has tightened, see

    This is an issue for discussion of a potential MutliError (or other name...) type API that allows the accumulation of multiple errors in a collection which still implements the error interface but allows retrieval of the individual errors.

    There are a few other options out there: but since already implements, in my opinion, the canonical best practices for error handling in Go it would be be nice if it included this feature.

    opened by kisielk 45
  • A Sprint function for services that use json logging

    A Sprint function for services that use json logging


    In the services that we run we utilise json logging for all of our error logs, I had a peruse and it seems that the current print functions either require a writer or go straight to os.Stderr.

    I think it would be very helpful for us, as well as for other users of this package, if there was a function that performs the same as fprint but returns a string for use.

    I've created a proof of concept here:

    For example output please see the tests.

    Thank you for your time!

    opened by dammitjim 31
  • Add support for Go 1.13 error chains

    Add support for Go 1.13 error chains

    Go 1.13 adds support for error chains to the standard libary's errors package. The new standard library functions require an Unwrap method to be provided by an error type. This change adds a new Unwrap method (identical to the existing Cause method) to the unexported error types.

    opened by jayschwa 28
  • Proposal: verbose errors

    Proposal: verbose errors

    In many cases when we're generating an error we know that the particular error, if it happens, is indicative of a bug. In those cases, it's very useful if the error message contains more information (like file:line).

    Errors might be handled at a different layer (e.g. sent out to a client using %s) where the original context of the error is lost.

    The proposal is to add a version of Errorf which results in a "verbose" error which automatically includes the file:line where it was generated as part of the error message.

    opened by RaduBerinde 28
  • Wrap(nil) should panic

    Wrap(nil) should panic

    I ran into an ugly bug today where I accidentally did this:

    err := stuff()
    if err != nil {
      return err
    result := moreStuff()
    if len(result.Failures) > 0 {
      // ... do stuff with failures ...
      return errors.Wrap(err, "Oops")

    This returns nil because err is nil. The code wanted to make a new err, but it didn't. Due to Go's error conventions, you tend to have a single shared err shared across nested scopes like this, and one has to be careful about what it contains. It took me 10 minutes to realize that err was nil here.

    In my opinion, Wrap(nil) should panic, because it makes no sense. The intent of the caller is clearly to wrap an error value (you shouldn't call Wrap if you don't have an error value), and you're telling it to wrap something that doesn't exist. I don't think this is controversial, but I think that, at best, it should return a new error with a nil cause.

    I can see an opposite argument that "blanket wrapping" allowed:

    return errors.Wrap(doStuff(), "it failed")

    However, I think that's a special cause that ought to be relegated to something like MaybeWrap().

    opened by atombender 20
  • Cause() vs RootCause()

    Cause() vs RootCause()

    I just came across this package and wondering why package's Cause() function returns the root cause and not just the cause of the passed error value? I can imagine a situation where I want to inspect the cause of the error and check for some additional information in it, etc. So, to get that information I'll have to do a check for Cause() presence myself, call it, do a type check for additional information methods and only then call them. An additional method that returns the cause might be useful here.

    ps. I wonder why this is not part of the standard library. Seems to be a very useful pattern.

    opened by ash2k 20
  • Proposal: Error aggregation

    Proposal: Error aggregation

    It would be nice if we could have a aggregate error struc for handling and propagating multiple errors. Internally it would have a list of errors, which can be appended. This struct has only to implement the Error() interface in order to be a error. The following signatures could be supported:

      Append(err error)  // in order to append errors to the aggregate
      Count() int   // in order to provide a way to check if errors exist
      Error() string  // in order to implement the Error interface
    opened by mantzas 15
  • Proposal: errors' context

    Proposal: errors' context


    What do you think of errors' contexts like net/context or simple map[string]interface{} stored with the original error? It would be really handy; example:

    var ErrNotFound = error.New("Page not found!")
    return errors.Wrap(ErrNotFound,pageTitle).WithContext(`http`,404)

    this way the imaginary http handler won't need to know about ErrNotFound; it would just grab the value from the context. It could be even better:

    var ErrNotFound = errors.Wrap(error.New("Page not found!"),"").WithContext(`http`,404)
    return errors.Wrap(ErrNotFound,pageTitle)

    however, this approach would lose stack data; it would require the stored stack's reset.

    The context or map can be initiated on demand (when adding first value), so it wouldn't create some significant overhead if context is not used.

    opened by utrack 15
  • Cause() behavior has changed

    Cause() behavior has changed


    after merging #215, I got some test failures of code that calls errors.Cause(err) where err is returned by some stdlib API: in my case err is returned by net.Conn.Write(), and errors.Cause(err) used to return a net.OpError instance, whereas it now returns a syscall.Errno instance.

    I understand the reason for the change, but just wanting to highlight this is introduces backward-incompatible behavior, at least for some consumers.

    YMMV re fixing this issue. Other people might find it useful to read, if the stumble upon the same regression.

    opened by freeekanayaka 11
  • Revert change to errors.Frame's type

    Revert change to errors.Frame's type

    In #183 the definition of errors.Frame was altered to type Frame runtime.Frame. This was necessary because of the changes to mid stack inlining in Go 1.12 and the deprecation of runtime.FuncForPC. suggests that it may be possible to continue to use runtime.FuncForPC. If this CL lands #183 should be mostly reverted for the 1.0 release.

    A future v2 release would probably drop the use of runtime.FuncForPC and redeclare errors.Frame as an opaque struct.

    opened by davecheney 11
  • Future of pkg/errors after proposal ?

    Future of pkg/errors after proposal ?

    How do you see the future of pkg/errors after the proposal for go1.13 ? That will even works with older version of go

    opened by flibustenet 10
  • Package errors looking for new maintainers

    Package errors looking for new maintainers


    Quite clearly this package has been unmaintained for a long time. There are two main reasons for this (along with several others — waves in the general direction of life)

    1. I had hoped that with the integration of some of the ideas from this package into Go 1.8 (I think) then the use of and need for this package would decrease. Sadly for whatever reason Go errors did not obtain the feature that this package was built for — stack traces on errors, so the need for this package remained.
    2. I no longer use this package, in fact I no longer wrap errors. This sounds like a grandiose claim, and it may be my quirky coding style (my other views on error handling are hardly commonplace), so I don’t mean this comment to be a judgement on anyone who uses this package and enjoys it. It’s simply that it’s hard to make time to work on something which I no longer believe in.

    Having got this off my chest, I recognise that this package holds a useful place in the Go ecosystem so it deserves more attention than it’s got over the last few years.

    To that end, I welcome expressions of interest in the comments below.

    Thank you

    opened by davecheney 4
  • `Errorf` should be able to wrap errors

    `Errorf` should be able to wrap errors

    I expected Errorf to mimic fmt.Errorf's behavior of wrapping errors. Alas, that was not the case. I was wondering if this is intentional or not. If it's intentional, then is there a way of formatting wrapping errors as '(wrapped error): outer error'?

    Here's a playground link explaining what I'm talking about.

    opened by osamaadam 4
  • Wrap() duplicates call stack

    Wrap() duplicates call stack

    I am currently considering using pkg/errors. However, I have a question, so I'm leaving a question.

    I ran the example code and expected the output shown in the code comments. However, if you look at the output attached below, you can see that the output is completely different. The problem is that duplicate stacks are displayed.

    And this also happens when I wrap the error passed to New() and WithStack(). Is this the intended behavior?

    Environment: pkg/errors version: 0.9.1 Go version: 1.16 OS version: macOS Big Sur 11.0.1

    My output:

    opened by dc7303 6
  • return *stack instead of stack

    return *stack instead of stack

    Hi, I see that the callers in the source code return *stack instead of stack. Why does this happen?

    func callers() *stack {
    	const depth = 32
    	var pcs [depth]uintptr
    	n := runtime.Callers(3, pcs[:])
    	var st stack = pcs[0:n]
    	return &st
    opened by simon28082 2
  • How to change format return wrapped error message

    How to change format return wrapped error message

    how can i change format return error message, to this

    func (w *withMessage) Error() string { return w.cause.Error()+ " | " + w.msg }

    opened by putrafajarh 2
  • v0.9.1(Jan 14, 2020)

    pkg/errors 0.9.1 is a bug fix release for errors 0.9.0. This restore the previous behaviour on Cause method, this behaviour was changed on the PR: #215 and many breaking changes was produced by that.

    Source code(tar.gz)
    Source code(zip)
  • v0.9.0(Jan 12, 2020)

    errors 0.9.0 is a preparation release for a 1.0 final release. Also we were working on removing support for Go 1.8, 1.9 and 1.10 and earlier, and become compatible this package with new way of errors on Go 1.13.

    We tried to move into runtime.CallerFrames but this was not possible, you can show the explanation here: Issue 188.

    The motivation for do the backward compatible this package with Go 1.13 is that you can migrate the easy way for this to the new way.

    Now you could use the methods, Is and As, and the Unwrap() interface like on the standard library.

    The method Cause is now compatible with fmt.Errorf("%w", err) and with the Unwrap() interface.

    On the same way the methods related with wrapping on this package now are compatible with Cause and Unwrap() interface.


    • .travis.yml Now use make file.
    • reduce allocations when printing stack traces. Thanks @cstockton
    • Reduce allocations in Stacktrace.Format
    • Add Support to Go 1.13. Thanks @jayschwa, @Sherlock-Holo and @puellanivis.
    • Add json.Marshaler support to the Frame type. Thanks @flimzy

    Bugs fixed

    • .travis.yml Adjust Go versions. Thanks @komuw, @aperezg
    • minor fix in an example to print Stack Trace. Thanks @bep.
    • Remove not necessary code.
    • Clean up documentation. Thanks @seh.
    Source code(tar.gz)
    Source code(zip)
  • v0.8.1(Jan 5, 2019)

    pkg/errors 0.8.1 is a bug fix release for errors 0.8.0. It will be the last version to support Go 1.8 and below. pkg/errors 0.9 and above will require Go 1.9 for the new runtime.CallersFrames API.

    pkg/errors 0.8.1 also adds one new feature, errors.WithMessagef. Ideally this would be held over til 0.9, but that complicates the switch to runtime.CallersFrames.


    • Added errors.WithMessagef. Thanks @chemicL.

    Bugs fixed

    • .travis.yml. Adjust Go versions. Thanks @AlekSi, @dvrkps, @HaraldNordgren, and @komuw
    • Fixed gofmt. Thanks @tariq1890
    • Copyedit the package documentation. Thanks @seh, @TomSweeneyRedHat, @nicksnyder, and @beono
    • Remove unreachable code. Thanks @philoserf and @haya14busa
    • Move benchmark error sink to global variable. Thanks @bradleyfalzon
    • Fix minor newline consistency issues in test files. Thanks @nmiyake
    • Add doc comment for exported Format func. Thanks @mrhwick and @ihrwein
    Source code(tar.gz)
    Source code(zip)
  • v0.8.0(Sep 29, 2016)

    What's new since version 0.7.1

    errors 0.8.0 decomposes Wrap (and Wrapf) into their component operations, namely adding a message to an error, and adding a stack trace to an error, which were previously merged into a single operation.

    This is accomplished by adding two top level functions, errors.WithMessage and errors.WithStack, and rewriting Wrap and Wrapf in terms of these operations.

    The motivation for this change was need to treat each of the following operations as distinct:

    • Adding a context message to an existing error without altering the stack trace.
    • Adding a stack trace to an existing error without the requirement of adding an additional message.
    • Retrieving the immediate cause of an error; popping one element of the error stack.

    The addition of WithStack and WithMessage increases the surface area of this package by two methods, after long discussions at GopherCon 2016 it was felt strongly that destructuring the operation of Wrap and Wrapf was necessary.

    For the moment Wrap and Wrapf remain, but depending on your feedback may be deprecated in future releases. Please leave comments via the issue link.

    Thanks to @nmiyake and @fabstu for their assistance in preparing this release.

    Bug fixes

    • Add Go 1.7.1 to .travis.yml. Thanks @Thomasdezeeuw
    Source code(tar.gz)
    Source code(zip)
  • v0.7.1(Aug 22, 2016)

    What's new since version 0.7.0

    0.7.1 is a minor release in the 0.7 series which contains bugfixes, documentation improvements and cleanups and some internal refactoring.


    • Rename StackTrace interface to stacktracer in docs and examples.
    • Capitalise first letter of trace in examples. Thanks @jongillham
    • Wrapped errors now print full stacktrace.
    • Documentation improvements, #69. Thanks @AlekSi
    • Added benchmarks comparing stack trace performance. Fixes #72. Thanks @kardianos

    Bug fixes

    • Fix %q format for wrapped errors. Thanks @greensnark
    • Remove trailing newline from LICENSE file. Thanks @vbatts
    • Tests now pass when pkg/errors is vendored. Fixes #77. Thanks @exp
    • Fix the %q format for errors so it puts "" around the output (caused by a bug introduced between 0.7.0 and 0.7.1). Thanks @ncw
    Source code(tar.gz)
    Source code(zip)
  • v0.7.0(Jun 14, 2016)

    What's new since version 0.6.0

    0.7.0 removes the deprecated errors.Location and errors.Stack interfaces, and the errors.Fprint helper. Types returned from this package now implement the fmt.Formatter interface and can print themselves when passed to fmt.Printf and friends.

    For example:

    • fmt.Printf("%s\n", err) will print the message of the error as per normal, recursive if the underlying error has a Cause method.
    • fmt.Printf(%v\n", err) operates the same as %s.
    • fmt.Printf(%+v\n", err) prints the error message as above, then prints a stack trace of the point that the error was created with errors.New, errors.Errorf, etc.

    This new behaviour is described in this blog post.

    Other changes in 0.7.0 include:

    • The Stacktrace() []Frame interface method was renamed to StackTrace() StackTrace. Please note the change in capitalisation. The previous interface was added in 0.6.0 so hopefully this change will not cause to many breaking changes. The name and signature of the method is not expected to change again in the future. Fixes #50.

    Bug fixes

    • incorrectly reported the licence of this package as MIT, not BSD 2 clause, this has been rectified. Thanks @anthonyfok. Fixes #41.
    Source code(tar.gz)
    Source code(zip)
  • v0.6.0(Jun 7, 2016)

    What's new since version 0.5.1

    The 0.6.0 release is a transitional release aimed at exposing the error's call stack, introduced in 0.5.0, to the caller.

    0.6.0 is the last release that will support the errors.Fprint helper function. This function will be removed in version 0.7 and will be replaced with a more flexible option based on the fmt.Formatter interface.

    Many thanks to @ChrisHines for inspiration, via his go-stack/stack package, and for his thoughtful review feedback.

    Deprecation notice

    The following symbols have been deprecated and will be removed in future releases.

    • errors.Fprintf will be removed in the 0.7 release. Read on for more details.
    • The Location interface,
    type location interface {
            Location() (string, int)

    is deprecated and will not be recognised in future releases. The replacement is

    fmt.Sprintf("%+v", err.Stacktrace()[0])

    That is, pass the topmost element of error's stack trace (assuming it has a Stacktrace() []Frame method) to fmt and print it with the %+v verb.

    • The Stack interface,
    type stack interface {
            Stack() []uintptr

    is deprecated and will not be recognised in future releases. Callers should use the new Stacktrace interface described below.

    New features

    • Stacktrace interface. As a replacement for the deprecated Stack() []uintptr interface, implementations in this package now support a Stacktrace interface
    type Stacktrace interface {
             Stacktrace() []Frame

    Calling this method returns a slice of Frame values, the most recent on the top. See #37

    • Frame values replace raw uintptr's (representing program counters) providing a type which implement the fmt.Formatter interface, which in turn exposes various aspect of a call frame (name, source file and line, etc) via the fmt package. See also #37
    • The name of the formal parameter to Wrap and Wrapf has been renamed from cause to err. This reflects the nature of these functions; to create a stack of errors. Apparently this also helps editor auto completion. Thanks @matryer. Fixes #32
    Source code(tar.gz)
    Source code(zip)
  • v0.5.1(May 24, 2016)

  • v0.5.0(May 23, 2016)

    What's new

    • New, Errorf, Wrap, and Wrapf, now store the stack trace of their caller (currently limited to a depth of 32). This can be retrieved by asserting for the following interface
    type Stack interface {
            Stack() []uintptr

    The resulting []uintptr is the same format as runtime.Callers. At the moment there are no helpers to inspect this information.

    Source code(tar.gz)
    Source code(zip)
  • v0.4.0(May 11, 2016)

    What's new

    • Remove the errors.Print helper, callers should use errors.Fprint(os.Stderr, err) as a replacement. See #23 for details
    • now has syntax highlighting. Thanks @mustafaakin
    • Package short description has been revised based. See #24 for details.
    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(May 2, 2016)

  • v0.2.0(Apr 25, 2016)

    What's new

    • Added Wrapf method which takes the usual fmt.Printf arguments. Thanks @umairidris. Fixes #6
    • pkg/errors now has an A+ Go report card. Thanks @umairidris

    Bug fixes since 0.1.0

    • Wrap would incorrect interpret fmt like verbs as format arguments, corrupting the error message. Thanks @enisoc
    • errors.loc.Location (and errors.Fprint) now more reliably detect the full package path, even in the presence of vendoring or multiple GOPATH segments. Thanks @ChrisHines. Fixes #8
    Source code(tar.gz)
    Source code(zip)
Artisanal, hand crafted, barrel aged, Go packages
Simple, intuitive and effective error handling for Go

Error Handling with eluv-io/errors-go The package eluv-io/errors-go makes Go error handling simple, intuitive and effective. err := someFunctionThatCa

Eluvio 0 Jan 19, 2022
A comprehensive error handling library for Go

Highlights The errorx library provides error implementation and error-related utilities. Library features include (but are not limited to): Stack trac

Joom 922 Jan 6, 2023
Declarative error handling for Go.

ErrorFlow Declarative error handling for Go. Motivation Reading list: Don't defer Close() on writable files Error Handling — Problem Overview Proposal

Serhiy T 8 Mar 3, 2022
Generic error handling with panic, recover, and defer.

Generic error handling with panic, recover, and defer.

Marcos César de Oliveira 21 Aug 25, 2022
brief: a piece of error handling codelet

brief a piece of error handling codelet. this code only demonstrates how to hide sql.ErrNoRows to the caller. the Get() method defined in the pkg/proj

null 0 Oct 30, 2021
🥷 CError (Custom Error Handling)

?? CError (Custom Error Handling) Installation Via go packages: go get Usage Here is a sample CError uses: import ( "gi

Rıdvan ÖZTURAÇ 3 Sep 21, 2022
Errors - A lib for handling error gracefully in Go

?? Errors Errors 是一个用于优雅地处理 Go 中错误的库。 Read me in English ??‍ 功能特性 优雅地处理 error,嗯,

水不要鱼 1 Jan 17, 2022
Error handling hook & helper function to simplify writing API handler methods in Go.

Error handling hook & helper function to simplify writing API handler methods in Go.

Steven Frew 0 Jan 19, 2022
Try - Idiomatic monadic-ish error handling for go

Try Idiomatic monadic-ish error handling for go. Examples import

Sam Riyad 0 Jan 24, 2022
Go error library with error portability over the network

cockroachdb/errors: Go errors with network portability This library aims to be used as a drop-in replacement to and Go's standar

CockroachDB 1.5k Dec 29, 2022
Wraps the normal error and provides an error that is easy to use with net/http.

Go HTTP Error Wraps the normal error and provides an error that is easy to use with net/http. Install go get -u Usage

Yuto Watanabe 0 Dec 20, 2021
Reduce debugging time while programming Go. Use static and stack-trace analysis to determine which func call causes the error.

Errlog: reduce debugging time while programming Introduction Use errlog to improve error logging and speed up debugging while you create amazing code

Martin Joly 412 Nov 18, 2022
A drop-in replacement for Go errors, with some added sugar! Unwrap user-friendly messages, HTTP status code, easy wrapping with multiple error types.

Errors Errors package is a drop-in replacement of the built-in Go errors package with no external dependencies. It lets you create errors of 11 differ

Kamaleshwar 47 Dec 6, 2022
A Go (golang) package for representing a list of errors as a single error.

go-multierror go-multierror is a package for Go that provides a mechanism for representing a list of error values as a single error. This allows a fun

HashiCorp 1.8k Jan 1, 2023
Error tracing and annotation.

errors -- import "" The errors package provides a way to create and diagnose errors. It is compatible with the usual Go error idi

Juju 226 Nov 3, 2022
A flexible error support library for Go

errors Please see for info License Copyright (C) 2014 Space Monkey, Inc. Licensed under the Apache Li

Space Monkey Go 168 Nov 3, 2022
A powerful, custom error package for Go

custom-error-go A powerful, custom error package for Go Detailed explanation:

Abhinav Bhardwaj 12 Apr 19, 2022
Go extract error codes

go-extract-error-codes Overview This library helps to extract possible error codes from configured go-restful applications quality level: PoC High Lev

AccelByte Inc 0 Nov 24, 2021
Error interface wrappers for Google's errdetails protobuf types, because they're handy as heck and I want to use them more

Error interface wrappers for Google's errdetails protobuf types, because they're handy as heck and I want to use them more

Claudia Hardman 1 Nov 18, 2021