├── .gitignore ├── doc.go ├── go.mod ├── go.sum ├── .github ├── dependabot.yml └── workflows │ └── test.yml ├── CONTRIBUTING.md ├── .golangci.yaml ├── status.go ├── status_test.go ├── errors_test.go ├── errors.go ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | # Test binary, built with `go test -c` 2 | *.test 3 | 4 | .idea 5 | *.iml 6 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Package serrors is a collection of utilities for creating and working with errors. 2 | package serrors 3 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/morningconsult/serrors 2 | 3 | go 1.13 4 | 5 | require github.com/google/go-cmp v0.6.0 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= 2 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= 3 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gomod 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | labels: 9 | - dependencies 10 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | All contributions are welcome and appreciated. Consider opening an issue before 4 | working on a pull request to make sure your change is in alignment with the 5 | project. 6 | 7 | ## Local Development 8 | 9 | To test code locally, you will need `go` installed locally: 10 | 11 | ```sh 12 | go test ./... 13 | ``` 14 | 15 | And to lint, you will need `golangci-lint` installed. To run: 16 | 17 | ```sh 18 | golangci-lint run ./... 19 | ``` 20 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | push: 5 | tags: 6 | - v* 7 | branches: 8 | - main 9 | pull_request: 10 | 11 | permissions: 12 | contents: read 13 | 14 | jobs: 15 | test: 16 | strategy: 17 | matrix: 18 | go-version: 19 | - '1.23' 20 | - '1.24' 21 | os: 22 | - ubuntu-latest 23 | - macos-latest 24 | - windows-latest 25 | runs-on: ${{ matrix.os }} 26 | steps: 27 | - uses: actions/setup-go@v5 28 | with: 29 | go-version: ${{ matrix.go-version }} 30 | check-latest: true 31 | - uses: actions/checkout@v4 32 | - run: go test ./... 33 | 34 | lint: 35 | runs-on: ubuntu-latest 36 | steps: 37 | - uses: actions/setup-go@v5 38 | with: 39 | go-version: '1.24' 40 | check-latest: true 41 | - uses: actions/checkout@v4 42 | - uses: golangci/golangci-lint-action@v7 43 | with: 44 | version: v2.0.2 45 | -------------------------------------------------------------------------------- /.golangci.yaml: -------------------------------------------------------------------------------- 1 | version: "2" 2 | issues: 3 | max-same-issues: 0 4 | 5 | linters: 6 | enable: 7 | - bodyclose 8 | - errcheck 9 | - errchkjson 10 | - exptostd 11 | - fatcontext 12 | - gocognit 13 | - gocritic 14 | - gocyclo 15 | - godot 16 | - gosec 17 | - lll 18 | - mirror 19 | - misspell 20 | - nakedret 21 | - nilnesserr 22 | - nolintlint 23 | - perfsprint 24 | - prealloc 25 | - revive 26 | - sloglint 27 | - unconvert 28 | - unparam 29 | - usetesting 30 | settings: 31 | errcheck: 32 | exclude-functions: 33 | # Errors we wouldn't act on after checking 34 | - (*database/sql.DB).Close 35 | - (*database/sql.Rows).Close 36 | - (io.Closer).Close 37 | - (*os.File).Close 38 | - (net/http.ResponseWriter).Write 39 | - io.WriteString(net/http.ResponseWriter) 40 | - fmt.Fprint(net/http.ResponseWriter) 41 | - fmt.Fprintf(net/http.ResponseWriter) 42 | - fmt.Fprintln(net/http.ResponseWriter) 43 | 44 | # Handled by errchkjson 45 | - encoding/json.Marshal 46 | - encoding/json.MarshalIndent 47 | - (*encoding/json.Encoder).Encode 48 | gocognit: 49 | min-complexity: 10 50 | gocyclo: 51 | min-complexity: 10 52 | govet: 53 | enable: 54 | - shadow 55 | nakedret: 56 | max-func-lines: 0 57 | revive: 58 | confidence: 0 59 | sloglint: 60 | args-on-sep-lines: true 61 | no-mixed-args: false 62 | exclusions: 63 | generated: strict 64 | rules: 65 | - linters: 66 | - bodyclose 67 | - gocognit 68 | - gocyclo 69 | - gosec 70 | - lll 71 | - prealloc 72 | path: _test\.go 73 | 74 | # Overly picky 75 | - linters: [revive] 76 | path: _test\.go 77 | text: unused-parameter 78 | 79 | # Duplicates of errcheck 80 | - linters: [gosec] 81 | text: 'G104: Errors unhandled' 82 | - linters: [gosec] 83 | text: 'G307: Deferring unsafe method' 84 | 85 | # Contexts are best assigned defensively 86 | - linters: [ineffassign] 87 | text: ineffectual assignment to `ctx` 88 | - linters: [revive] 89 | text: "unused-parameter: parameter 'ctx' seems to be unused" 90 | - linters: [staticcheck] 91 | text: 'SA4006: this value of `ctx` is never used' 92 | 93 | formatters: 94 | enable: 95 | - gci 96 | - gofumpt 97 | settings: 98 | gci: 99 | sections: 100 | - standard 101 | - default 102 | - localmodule 103 | exclusions: 104 | generated: strict 105 | -------------------------------------------------------------------------------- /status.go: -------------------------------------------------------------------------------- 1 | package serrors 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "net/http" 7 | ) 8 | 9 | // StatusCoder represents something that returns a status code. 10 | type StatusCoder interface { 11 | StatusCode() int 12 | } 13 | 14 | type statusError struct { 15 | HTTPStatusCode int 16 | Err error 17 | } 18 | 19 | var _ StatusCoder = statusError{} 20 | 21 | // NewStatusError returns an error that bundles an HTTP status code. The stack 22 | // trace will be captured. 23 | func NewStatusError(code int, msg string) error { 24 | return statusError{ 25 | HTTPStatusCode: code, 26 | Err: &stackErr{ 27 | err: errors.New(msg), 28 | trace: buildStackTrace(), 29 | }, 30 | } 31 | } 32 | 33 | // NewStatusErrorf returns an error that bundles an HTTP status code, sharing 34 | // fmt.Errorf semantics. The stack trace will be captured if not already 35 | // present. 36 | func NewStatusErrorf(code int, format string, a ...interface{}) error { 37 | err := fmt.Errorf(format, a...) 38 | 39 | // it's possible that there was already a StackTracer in the unwrap chain in the fmt.Errorf. 40 | // if so, use that stacktracer in the StackErr. 41 | var st StackTracer 42 | if errors.As(err, &st) { 43 | return statusError{ 44 | HTTPStatusCode: code, 45 | Err: &stackErr{ 46 | err: err, 47 | stackTracer: st, 48 | }, 49 | } 50 | } 51 | 52 | return statusError{ 53 | HTTPStatusCode: code, 54 | Err: &stackErr{ 55 | err: err, 56 | trace: buildStackTrace(), 57 | }, 58 | } 59 | } 60 | 61 | // WithStatus bundles an error with an HTTP status code. The stack trace will 62 | // be captured if not already present. 63 | func WithStatus(code int, err error) error { 64 | if err == nil { 65 | panic("cannot attach status to nil error") 66 | } 67 | 68 | var se StackTracer 69 | if errors.As(err, &se) { 70 | return statusError{ 71 | HTTPStatusCode: code, 72 | Err: err, 73 | } 74 | } 75 | 76 | return statusError{ 77 | HTTPStatusCode: code, 78 | Err: &stackErr{ 79 | err: err, 80 | trace: buildStackTrace(), 81 | }, 82 | } 83 | } 84 | 85 | // NewFromStatus creates a new StatusError with the given status code and the 86 | // HTTP status text from the standard library. 87 | func NewFromStatus(code int) error { 88 | msg := http.StatusText(code) 89 | if msg == "" { 90 | msg = "Unknown Status Error" 91 | } 92 | 93 | return statusError{ 94 | HTTPStatusCode: code, 95 | Err: &stackErr{ 96 | err: errors.New(msg), 97 | trace: buildStackTrace(), 98 | }, 99 | } 100 | } 101 | 102 | // Error returns the underlying error as a string. Status code information 103 | // will not be captured. 104 | func (s statusError) Error() string { 105 | if s.Err == nil { 106 | return "" 107 | } 108 | return s.Err.Error() 109 | } 110 | 111 | // Unwrap returns the underlying error. 112 | func (s statusError) Unwrap() error { 113 | return s.Err 114 | } 115 | 116 | // StatusCode returns the HTTP status code captured when the error was created. 117 | func (s statusError) StatusCode() int { 118 | return s.HTTPStatusCode 119 | } 120 | -------------------------------------------------------------------------------- /status_test.go: -------------------------------------------------------------------------------- 1 | package serrors_test 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "net/http" 7 | "testing" 8 | 9 | "github.com/google/go-cmp/cmp" 10 | 11 | "github.com/morningconsult/serrors" 12 | ) 13 | 14 | func TestNewStatusError(t *testing.T) { 15 | code := 400 16 | msg := "oh no" 17 | err := serrors.NewStatusError(code, msg) 18 | 19 | var sc serrors.StatusCoder 20 | if !errors.As(err, &sc) { 21 | t.Fatal("err is not a StatusCoder") 22 | } 23 | 24 | if got := sc.StatusCode(); got != code { 25 | t.Errorf("want code %d, got %d", code, got) 26 | } 27 | 28 | if err.Error() != msg { 29 | t.Errorf("want error %q, got %q", msg, err.Error()) 30 | } 31 | } 32 | 33 | func TestNewStatusErrorf(t *testing.T) { 34 | code := 400 35 | err := serrors.NewStatusErrorf(code, "foo: %s", "bar") 36 | 37 | var sc serrors.StatusCoder 38 | if !errors.As(err, &sc) { 39 | t.Fatal("err is not a StatusCoder") 40 | } 41 | 42 | if got := sc.StatusCode(); got != code { 43 | t.Errorf("want code %d, got %d", code, got) 44 | } 45 | 46 | wantMsg := "foo: bar" 47 | if msg := err.Error(); msg != wantMsg { 48 | t.Errorf("want message %q, got %q", wantMsg, msg) 49 | } 50 | } 51 | 52 | func TestNewStatusErrorf_wraps_stack_tracer(t *testing.T) { 53 | code := 400 54 | 55 | err := serrors.New("oh no") 56 | err = serrors.NewStatusErrorf(code, "wrapping: %w", err) 57 | 58 | var sc serrors.StatusCoder 59 | if !errors.As(err, &sc) { 60 | t.Fatal("err is not a StatusCoder") 61 | } 62 | 63 | if got := sc.StatusCode(); got != code { 64 | t.Errorf("want code %d, got %d", code, got) 65 | } 66 | 67 | wantMsg := "wrapping: oh no" 68 | if msg := err.Error(); msg != wantMsg { 69 | t.Errorf("want message %q, got %q", wantMsg, msg) 70 | } 71 | 72 | wantVerbose := traceLine(55) 73 | got := traceError(t, err) 74 | if diff := cmp.Diff(wantVerbose, got); diff != "" { 75 | t.Errorf("results differ (-want +got):\n%s", diff) 76 | } 77 | } 78 | 79 | func TestWithStatus(t *testing.T) { 80 | err := serrors.New("test message") 81 | err = serrors.WithStatus(200, err) 82 | 83 | got := traceError(t, err) 84 | want := traceLine(80) 85 | if diff := cmp.Diff(want, got); diff != "" { 86 | t.Errorf("results differ (-want +got):\n%s", diff) 87 | } 88 | } 89 | 90 | func TestWithStatus_nil(t *testing.T) { 91 | defer func() { 92 | wantPanic := "cannot attach status to nil error" 93 | if r := recover(); r == nil || r != wantPanic { 94 | t.Errorf("want panic %q, got %q", wantPanic, r) 95 | } 96 | }() 97 | serrors.WithStatus(200, nil) //nolint:errcheck 98 | } 99 | 100 | func TestNewFromStatus(t *testing.T) { 101 | tests := []struct { 102 | status int 103 | wantText string 104 | }{ 105 | {http.StatusOK, http.StatusText(http.StatusOK)}, 106 | {http.StatusTeapot, http.StatusText(http.StatusTeapot)}, 107 | {-1, "Unknown Status Error"}, 108 | } 109 | 110 | for _, tt := range tests { 111 | t.Run(tt.wantText, func(t *testing.T) { 112 | err := serrors.NewFromStatus(tt.status) 113 | var sc serrors.StatusCoder 114 | if !errors.As(err, &sc) { 115 | t.Fatalf("want status error, got %T", err) 116 | } 117 | 118 | if sc.StatusCode() != tt.status { 119 | t.Errorf("want status %d, got %d", tt.status, sc.StatusCode()) 120 | } 121 | 122 | if err.Error() != tt.wantText { 123 | t.Errorf("want error %q, got %q", tt.wantText, err.Error()) 124 | } 125 | 126 | got := traceError(t, err) 127 | want := traceLine(112) 128 | if diff := cmp.Diff(want, got); diff != "" { 129 | t.Errorf("results differ (-want +got):\n%s", diff) 130 | } 131 | }) 132 | } 133 | } 134 | 135 | func Test_statusError_Is(t *testing.T) { 136 | err := errors.New("oh boy") 137 | err400 := serrors.WithStatus(400, err) 138 | 139 | if !errors.Is(err400, err400) { 140 | t.Error("error does not equal itself") 141 | } 142 | 143 | err500 := serrors.WithStatus(500, err) 144 | if errors.Is(err400, err500) { 145 | t.Error("status codes were not compared") 146 | } 147 | 148 | wrapped := fmt.Errorf("wrapped: %w", err400) 149 | if !errors.Is(wrapped, err400) { 150 | t.Error("not equal to wrapped version") 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /errors_test.go: -------------------------------------------------------------------------------- 1 | package serrors_test 2 | 3 | import ( 4 | "errors" 5 | "runtime" 6 | "strings" 7 | "testing" 8 | 9 | "github.com/google/go-cmp/cmp" 10 | 11 | "github.com/morningconsult/serrors" 12 | ) 13 | 14 | func Test_stackErr(t *testing.T) { 15 | e := serrors.New("new err") 16 | se := serrors.WithStack(e) 17 | want := traceLine(15) 18 | got := traceError(t, se) 19 | 20 | if diff := cmp.Diff(want, got); diff != "" { 21 | t.Errorf("stacktrace differs:\n%s", diff) 22 | } 23 | 24 | se2 := serrors.WithStack(se) 25 | if !errors.Is(se2, se) { 26 | t.Error("wrapping is not a noop") 27 | } 28 | } 29 | 30 | func TestSentinel(t *testing.T) { 31 | const msg = "This is a constant error" 32 | const s = serrors.Sentinel(msg) 33 | if s.Error() != msg { 34 | t.Errorf("want error %q, got %q", msg, s.Error()) 35 | } 36 | } 37 | 38 | func TestNew(t *testing.T) { 39 | err := serrors.New("test message") 40 | expected := traceLine(39) 41 | result := traceError(t, err) 42 | if diff := cmp.Diff(expected, result); diff != "" { 43 | t.Errorf("stacktrace differs\n%s", diff) 44 | } 45 | } 46 | 47 | func TestErrorf(t *testing.T) { 48 | data := []struct { 49 | name string 50 | formatString string 51 | values []interface{} 52 | wantMessage string 53 | wantTrace string 54 | }{ 55 | { 56 | "wrapped non-stack trace error", 57 | "this is an %s: %w", 58 | []interface{}{"error", errors.New("inner error")}, 59 | "this is an error: inner error", 60 | traceLine(80), 61 | }, 62 | { 63 | "wrapped stack trace error", 64 | "this is an %s: %w", 65 | []interface{}{"error", serrors.New("inner error")}, 66 | "this is an error: inner error", 67 | traceLine(65), 68 | }, 69 | { 70 | "no error", 71 | "this is an %s", 72 | []interface{}{"error"}, 73 | "this is an error", 74 | traceLine(80), 75 | }, 76 | } 77 | for _, v := range data { 78 | // produce the error outside the anon function below so we get the test 79 | // as the caller and not test.func1 80 | errOuter := serrors.Errorf(v.formatString, v.values...) 81 | t.Run(v.name, func(t *testing.T) { 82 | result := traceError(t, errOuter) 83 | if diff := cmp.Diff(v.wantTrace, result); diff != "" { 84 | t.Errorf("stacktrace differs\n%s", diff) 85 | } 86 | }) 87 | } 88 | } 89 | 90 | func TestSentinelComparisons(t *testing.T) { 91 | const s = serrors.Sentinel("This is a constant error") 92 | err := s 93 | if err != s { 94 | t.Errorf("should be the same") 95 | } 96 | if !errors.Is(err, s) { 97 | t.Errorf("should be the same") 98 | } 99 | err2 := serrors.Errorf("Wrapping error: %w", s) 100 | if !errors.Is(err2, s) { 101 | t.Errorf("should be there") 102 | } 103 | } 104 | 105 | func Test_stackErr_Is(t *testing.T) { 106 | err := serrors.New("foo") 107 | if !errors.Is(err, err) { 108 | t.Error("oops") 109 | } 110 | 111 | stdErr := errors.New("bar") 112 | wrappedErr := serrors.WithStack(stdErr) 113 | if !errors.Is(wrappedErr, stdErr) { 114 | t.Error("oops") 115 | } 116 | } 117 | 118 | func TestWithStackNil(t *testing.T) { 119 | if serrors.WithStack(nil) != nil { 120 | t.Error("Got non-nil for nil passed to WithStack") 121 | } 122 | } 123 | 124 | // traceLine formats a stack trace message based on the provided line for the 125 | // test, using the actual outside callers of the test. 126 | func traceLine(expectedLine int) string { 127 | pcs := make([]uintptr, 100) 128 | // start at 2, skipping runtime.Callers and this function 129 | n := runtime.Callers(2, pcs) 130 | frames := runtime.CallersFrames(pcs[:n]) 131 | 132 | str := strings.Builder{} 133 | frame, _ := frames.Next() 134 | frame.Line = expectedLine 135 | _ = serrors.PanicFormat.Execute(&str, frame) 136 | str.WriteByte('\n') 137 | 138 | for { 139 | frame, more := frames.Next() 140 | _ = serrors.PanicFormat.Execute(&str, frame) 141 | 142 | if !more { 143 | break 144 | } 145 | str.WriteByte('\n') 146 | } 147 | return str.String() 148 | } 149 | 150 | // traceError formats a stack trace from an error. 151 | func traceError(t *testing.T, err error) string { 152 | lines, err := serrors.Trace(err, serrors.PanicFormat) 153 | if err != nil { 154 | t.Fatal(err) 155 | } 156 | return strings.Join(lines, "\n") 157 | } 158 | -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | package serrors 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "fmt" 7 | "runtime" 8 | "text/template" 9 | ) 10 | 11 | // StackTracer defines an interface that's met by an error that returns a stacktrace. This is 12 | // intended to be used by errors that capture the stacktrace to the source of the error. Each 13 | // invocation of StackTrace() must return a new instance of *runtime.Frames, so that this method 14 | // can be invoked more than once (runtime.Frames uses internal iteration and has no way to reset 15 | // the iterator). 16 | type StackTracer interface { 17 | StackTrace() *runtime.Frames 18 | } 19 | 20 | // stackErr wraps an error with the stack location where the error occurred. 21 | type stackErr struct { 22 | err error 23 | trace []uintptr 24 | stackTracer StackTracer 25 | } 26 | 27 | // StackTrace returns the call stack frames for the StackErr. If this was the first StackTracer on 28 | // the unwrap chain, it captures when the StackErr was instantiated. If there was an earlier StackTracer, 29 | // the se.stackTracer field is set, and the StackTrace() is returned from it. 30 | // 31 | // A new instance of *runtime.Frames is created every time this method is run, since the struct tracks 32 | // its own offset and cannot be reused. 33 | func (se stackErr) StackTrace() *runtime.Frames { 34 | if se.stackTracer != nil { 35 | return se.stackTracer.StackTrace() 36 | } 37 | return runtime.CallersFrames(se.trace) 38 | } 39 | 40 | // Is implementation to properly handle two StackErr instances being compared to each other using errors.Is. 41 | // Both StackErr instances need to be unwrapped because the trace slice field makes the StackErr not comparable. 42 | func (se stackErr) Is(err error) bool { 43 | if err, ok := err.(stackErr); ok { 44 | return errors.Is(se.err, err.err) 45 | } 46 | return errors.Is(se.err, err) 47 | } 48 | 49 | // WithStack takes in an error and returns an error wrapped in a StackErr with the location where 50 | // an error was first created or returned from third-party code. If there is already an error 51 | // in the error chain that exposes a stacktrace via the StackTrace() method, WithStack returns 52 | // the passed-in error. If a nil error is passed in, nil is returned. 53 | func WithStack(err error) error { 54 | if err == nil { 55 | return nil 56 | } 57 | var se StackTracer 58 | if errors.As(err, &se) { 59 | return err 60 | } 61 | return stackErr{ 62 | err: err, 63 | trace: buildStackTrace(), 64 | } 65 | } 66 | 67 | func buildStackTrace() []uintptr { 68 | pc := make([]uintptr, 20) 69 | n := runtime.Callers(3, pc) 70 | pc = pc[:n] 71 | return pc 72 | } 73 | 74 | // New builds a StackErr out of a string. 75 | func New(msg string) error { 76 | return stackErr{ 77 | err: errors.New(msg), 78 | trace: buildStackTrace(), 79 | } 80 | } 81 | 82 | // Errorf wraps the error returned by fmt.Errorf in a StackErr. If there is an existing StackTracer 83 | // in the unwrap chain, its stack trace will be preserved. 84 | func Errorf(format string, vals ...interface{}) error { 85 | err := fmt.Errorf(format, vals...) 86 | // it's possible that there was already a StackTracer in the unwrap chain in the fmt.Errorf. 87 | // if so, use that stacktracer in the StackErr. 88 | var st StackTracer 89 | if errors.As(err, &st) { 90 | return stackErr{ 91 | err: err, 92 | stackTracer: st, 93 | } 94 | } 95 | return stackErr{ 96 | err: err, 97 | trace: buildStackTrace(), 98 | } 99 | } 100 | 101 | // Unwrap exposes the error wrapped by StackErr. 102 | func (se stackErr) Unwrap() error { 103 | return se.err 104 | } 105 | 106 | // Error is the marker interface for an error, it returns the wrapped error or an empty string if there is no 107 | // wrapped error. 108 | func (se stackErr) Error() string { 109 | if se.err == nil { 110 | return "" 111 | } 112 | return se.err.Error() 113 | } 114 | 115 | // StandardFormat is a one-line template used to convert a *runtime.Frame to a 116 | // string. Each entry is formatted as: 117 | // 118 | // FUNCTION_NAME (FILE_NAME:LINE_NUMBER) 119 | var StandardFormat = template.Must(template.New("standardFormat").Parse("{{.Function}} ({{.File}}:{{.Line}})")) 120 | 121 | // PanicFormat is a template resembling the output of a `panic` used to convert 122 | // a *runtime.Frame to a string. Each entry is formatted as: 123 | // 124 | // FUNCTION_NAME 125 | // FILE_NAME:LINE_NUMBER 126 | var PanicFormat = template.Must(template.New("standardFormat").Parse("{{.Function}}\n\t{{.File}}:{{.Line}}")) 127 | 128 | // Trace returns the stack trace information as a slice of strings formatted using the provided Go template. The valid 129 | // fields in the template are Function, File, and Line. See StandardFormat for an example. 130 | func Trace(e error, t *template.Template) ([]string, error) { 131 | var se StackTracer 132 | if !errors.As(e, &se) { 133 | return nil, nil 134 | } 135 | s := make([]string, 0, 20) 136 | frames := se.StackTrace() 137 | var b bytes.Buffer 138 | for { 139 | b.Reset() 140 | frame, more := frames.Next() 141 | err := t.Execute(&b, frame) 142 | if err != nil { 143 | return nil, WithStack(err) 144 | } 145 | s = append(s, b.String()) 146 | if !more { 147 | break 148 | } 149 | } 150 | return s, nil 151 | } 152 | 153 | // Sentinel is a way to turn a constant string into an error. It allows you to safely declare a 154 | // package-level error so that it can't be accidentally modified to refer to a different value. 155 | // 156 | // Deprecated: For package-scoped errors or other errors that should not have 157 | // stack traces, use the standard library's [errors.New]. 158 | type Sentinel string 159 | 160 | // Error is the marker interface for an error. This converts a Sentinel into a string for output. 161 | func (s Sentinel) Error() string { 162 | return string(s) 163 | } 164 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Go Report Card](https://goreportcard.com/badge/github.com/morningconsult/serrors)](https://goreportcard.com/report/github.com/morningconsult/serrors) 2 | # serrors 3 | 4 | serrors is a collection of utitilies for creating and working with errors. 5 | These include automatic stack traces based on ideas from 6 | and the ability to combine HTTP statuses with 7 | errors directly. 8 | 9 | ## Stack Traces 10 | 11 | One of the biggest differences between errors in Go and exceptions in other 12 | languages is that you don't get a stack trace with a Go error. `serrors` fixes 13 | this limitation. 14 | 15 | ### Creating Stack Traces 16 | 17 | The `serrors.WithStack` function takes an existing error and wraps it with a 18 | stack trace. This is meant for adapting errors returned by the standard library 19 | or third-party libraries when you have no other context to provide. If an error 20 | is passed to `serrors.WithStack` that already has an error that implements the 21 | `serrors.StackTracer` interface in its unwrap chain, the passed-in error is 22 | returned. If a `nil` error is passed to `serrors.WithStack`, `nil` is returned. 23 | These two rules make it possible to write the following code and not worry if 24 | there's already a stack trace (or no error) stored in `err`: 25 | 26 | ```go 27 | func DoSomething(input string) (string, error) { 28 | result, err := ThingToCall(input) 29 | return result, serrors.WithStack(err) 30 | } 31 | ``` 32 | 33 | If you want to wrap an existing error with your own contextual information, use 34 | `serrors.Errorf`. This works exactly like `fmt.Errorf`, only it wraps the passed-in 35 | error with a stack trace as well: 36 | 37 | ```go 38 | func DoSomething(input string) (string, error) { 39 | result, err := ThingToCall(input) 40 | if err != nil { 41 | err = serrors.Errorf("calling ThingToCall: %w", err) 42 | } 43 | return result, err 44 | } 45 | ``` 46 | 47 | If there's an error in the unwrap chain that implements the 48 | `serrors.StackTracer` interface, `serrors.Errorf` preserves the existing trace 49 | information. 50 | 51 | If you are creating a new error that's only a `string`, use `serrors.New`. This 52 | is a drop-in replacement for `errors.New`: 53 | 54 | ```go 55 | func DoSomething(input string) (string, error) { 56 | if input == "" { 57 | return "", serrors.New("cannot supply an empty string to DoSomething") 58 | } 59 | result, err := ThingToCall(input) 60 | return result, serrors.WithStack(err) 61 | } 62 | ``` 63 | 64 | Avoid declaring errors at the package scope using `serrors`, as the generated 65 | stack trace will be associated with the variable declaration rather than the 66 | location where the application error was encountered. For these cases, prefer 67 | the standard library's `errors.New` when declaring the package-scoped error, 68 | and then annotate that error where the stack trace should originate using a 69 | function such as `serrors.WithStack` or `serrors.Errorf` : 70 | 71 | ```go 72 | var ErrUnsupported = errors.New("unsupported") 73 | 74 | func DoSomething(input string) (string, error) { 75 | if input == "" { 76 | return serrors.Errorf("cannot supply an empty string to DoSomething: %w", ErrUnsupported) 77 | } 78 | result, err := ThingToCall(input) 79 | return result, serrors.WithStack(err) 80 | } 81 | ``` 82 | 83 | ### Using Stack Traces 84 | 85 | Once you have an error in your unwrap chain with a stack trace, there are three 86 | ways to get the trace back: 87 | 88 | #### `serrors.Trace` 89 | 90 | You can use the `serrors.Trace` function to get a `[]string` that contains each 91 | line of the stack trace: 92 | 93 | ```go 94 | s := serrors.New("This is a stack trace error") 95 | callStack, err := serrors.Trace(s, serrors.StandardFormat) 96 | fmt.Println(callStack) 97 | ``` 98 | 99 | `serrors.Trace` takes two parameters. The first is the error, and the second is 100 | a `text.Template`. There are two default templates defined. 101 | `serrors.PanicFormat` produces an output that resembles stack traces produced 102 | by the output of a `panic`, while `serrors.StandardFormat` provides a condensed 103 | single-line output. 104 | 105 | If you want to write your own template, there are three valid variables: 106 | 107 | - .Function (for the function name), 108 | - .File (for the file path and name) 109 | - .Line (for the line number). 110 | 111 | If you supply an error that doesn't have an `serrors.StackTracer` in its unwrap 112 | chain, `nil` is returned for both the slice of strings and the error. If an 113 | invalid template is supplied, `nil` is returned for the slice and the error is 114 | returned (wrapped in its own stack trace). Otherwise, the stack trace is 115 | returned as a slice of strings along with a `nil` error. 116 | 117 | Note that by default, the file path will include the absolute path to the file 118 | on the machine that built the code. If you want to hide this path, build using 119 | the `-trimpath` flag. 120 | 121 | #### `errors.As` 122 | 123 | Errors with stack traces produced by `serrors` will implement the 124 | `serrors.StackTracer` interface. You can use `errors.As` to cast the error and 125 | call `StackTrace()` directly: 126 | 127 | ```go 128 | err := serrors.New("This is a stack trace error") 129 | 130 | var stackTracer serrors.StackTracer 131 | if errors.As(err, &stackTracker) { 132 | frames := stackTracer.StackTrace() 133 | // ... 134 | } 135 | ``` 136 | 137 | #### Formatting Verb 138 | 139 | Errors with stack traces also implement the `fmt.Formatter` interface, so the 140 | `%+v` formatting directive can be used: 141 | 142 | ```go 143 | err := serrors.New("this is a stack trace error") 144 | fmt.Printf("%+v\n", err) 145 | ``` 146 | 147 | Unfortunately, `fmt` formatting does not unwrap errors, so if an error with a 148 | stack trace is wrapped using a non-`serrors` utility function such as 149 | `fmt.Errorf`, the stack trace will not be printed this way. For that reason, 150 | in situations where it is critical to ensure that the stack trace is recovered, 151 | one of the other two methods should be preferred. 152 | 153 | ## Status Errors 154 | 155 | Not all errors are equal; different errors mean different things. Some indicate 156 | a bug in the server, while others indicate bad data being passed in. HTTP 157 | status codes are used to indicate this at the web API tier, but there isn't an 158 | easy way to pass this information back to that layer. 159 | 160 | The `serrors` package includes three helpers to attach a status code directly 161 | to an error: 162 | 163 | - `serrors.WithStatus` takes an existing and attaches a status code. 164 | - `serrors.NewStatusError` creates a new error from a string. 165 | - `serrors.NewStatusErrorf` creates an error with `fmt.Errorf` semantics. 166 | 167 | For convenience, all helpers wrap errors with stack traces as well. 168 | 169 | The API allows an `int` to be passed in as a status code. By convention, these 170 | should use HTTP status codes exclusively. Any other status codes run the risk 171 | of violating expectations across application boundaries. 172 | 173 | In order to retrieve the status code from an error, you can use `errors.As`: 174 | 175 | ```go 176 | func HandleRequest(w http.ResponseWriter, r *http.Request) { 177 | err := ThingToCall() 178 | var sc serrors.StatusCoder 179 | switch { 180 | case errors.As(err, &sc): 181 | w.WriteHeader(sc.StatusCode()) 182 | case err != nil: 183 | w.WriteHeader(http.StatusInternalServerError) 184 | default: 185 | w.WriteHeader(http.StatusOK) 186 | } 187 | } 188 | ``` 189 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------