Skip to content

Commit

Permalink
Initial Import
Browse files Browse the repository at this point in the history
  • Loading branch information
calebcase committed Dec 5, 2022
0 parents commit 99d1afe
Show file tree
Hide file tree
Showing 16 changed files with 756 additions and 0 deletions.
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright 2022 Caleb Case <calebcase@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# oops

[![Go Reference](https://pkg.go.dev/badge/github.com/calebcase/oops.svg)](https://pkg.go.dev/github.com/calebcase/oops)
[![Go Report Card](https://goreportcard.com/badge/github.com/calebcase/oops)](https://goreportcard.com/report/github.com/calebcase/oops)

Oops implements the batteries that are missing from [errors][errors]:

* Stack traces: attach a stack trace to any error
* Chaining: combining multiple errors into a single stack of errors (as you
might want when handling the errors from disposing resources like
[file_close][file.Close()])
* Namespacing: create an error factory that prefixes errors with a given name
* Shadowing: hide the exact error behind a package level error (as you might
want when trying to stabilize your API's supported errors)

---

[errors]: https://pkg.go.dev/errors
[file_close]: https://pkg.go.dev/os#File.Close
99 changes: 99 additions & 0 deletions chain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package oops

import (
"fmt"
"strings"
)

// ChainError is a list of errors oldest to newest.
type ChainError []error

var _ error = ChainError{}
var _ unwrapper = ChainError{}

func (ce ChainError) Error() string {
return fmt.Sprintf("%v", ce)
}

func (ce ChainError) Unwrap() error {
if len(ce) == 0 || len(ce) == 1 {
return nil
}

if len(ce) == 2 {
return ce[1]
}

return ChainError(ce[1:])
}

// Format implements fmt.Format.
func (ce ChainError) Format(f fmt.State, verb rune) {
if len(ce) == 0 {
return
}

flag := ""
if f.Flag(int('+')) {
flag = "+"
}

if flag == "" {
fmt.Fprintf(f, "%"+string(verb), ce[0])

return
}

errs := make([]string, 0, len(ce))

fmt.Fprintf(f, "chain:\n")
for i, err := range ce {
lines := ErrorIndent(err, "%"+flag+string(verb), "··")

errs = append(errs, fmt.Sprintf("··[%d] %s", i, lines[0]))

if len(lines) > 1 {
errs = append(errs, lines[1:]...)
}
}

f.Write([]byte(strings.Join(errs, "\n")))
}

// Chain combines errors into a chain of errors. nil errors are removed.
func Chain(errs ...error) error {
if len(errs) == 0 {
return nil
}

if len(errs) == 1 {
return errs[0]
}

ce := ChainError{}

for _, err := range errs {
if err == nil {
continue
}

if peer, ok := err.(ChainError); ok {
ce = append(ce, peer...)

continue
}

ce = append(ce, err)
}

return ce
}

// ChainP combines errors into a chain of errors. nil errors are removed.
func ChainP(err *error, errs ...error) {
if err == nil {
return
}

*err = Chain(append([]error{*err}, errs...)...)
}
81 changes: 81 additions & 0 deletions chain_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package oops_test

import (
"context"
"encoding/json"
"errors"
"testing"

"github.com/calebcase/oops"
"github.com/stretchr/testify/require"
)

type closer struct {
open bool
}

func open() (*closer, error) {
return &closer{true}, nil
}

func (c *closer) Close(ctx context.Context) error {
c.open = false

return oops.New("close error")
}

func openclose() (err error) {
ctx := context.Background()

f, err := open()
if err != nil {
return err
}
defer func() {
err = oops.Chain(err, f.Close(ctx))
}()

return oops.New("openclose error")
}

func opencloseP() (err error) {
ctx := context.Background()

f, err := open()
if err != nil {
return err
}
defer func() {
oops.ChainP(&err, f.Close(ctx))
}()

return oops.New("openclose error")
}

func TestChain(t *testing.T) {
t.Run("Chain", func(t *testing.T) {
err := openclose()
werr := errors.Unwrap(err)

t.Logf("error: %T\n%+v\n", err, err)
require.Error(t, err)

t.Logf("wrapped error: %T\n%+v\n", werr, werr)
require.Error(t, werr)

bs, jerr := json.MarshalIndent(err, "", " ")
require.NoError(t, jerr)
t.Log(string(bs))
})

t.Run("ChainP", func(t *testing.T) {
err := opencloseP()
werr := errors.Unwrap(err)

t.Logf("error: %T\n%+v\n", err, err)
require.Error(t, err)

t.Logf("wrapped error: %T\n%+v\n", werr, werr)
require.Error(t, werr)
})
}
2 changes: 2 additions & 0 deletions doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Package oops implements the batteries missing from Package errors.
package oops
44 changes: 44 additions & 0 deletions error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package oops

import (
"encoding/json"
"fmt"
"strings"
)

// ErrorMarshalJSON uses e's json.Marshaler if it implements one otherwise it
// uses the output from e.Error() (marshalled into a JSON string).
func ErrorMarshalJSON(e error) (bs []byte, err error) {
if jm, ok := e.(json.Marshaler); ok {
bs, err = jm.MarshalJSON()
} else {
bs, err = json.Marshal(e.Error())
}

if err != nil {
return nil, err
}

return bs, nil
}

// ErrorLines returns the error's string in the given format as an array of
// lines.
func ErrorLines(err error, format string) []string {
return strings.Split(fmt.Sprintf(format, err), "\n")
}

// ErrorIndent returns the error's string prefixed by indent. The first line is
// not indented.
func ErrorIndent(err error, format, indent string) []string {
lines := ErrorLines(err, format)
for i, line := range lines {
if i == 0 {
continue
}

lines[i] = indent + line
}

return lines
}
11 changes: 11 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module github.com/calebcase/oops

go 1.19

require github.com/stretchr/testify v1.8.1

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
17 changes: 17 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Loading

0 comments on commit 99d1afe

Please sign in to comment.