Skip to content

Commit

Permalink
Merge pull request #8 from jelmersnoeck/add-vice-for-error
Browse files Browse the repository at this point in the history
Implement ForError function
  • Loading branch information
jbowes committed Jun 4, 2020
2 parents 9c14156 + a289348 commit a9ee44d
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 3 deletions.
22 changes: 22 additions & 0 deletions error.go
Expand Up @@ -57,3 +57,25 @@ func Seal(err error, v Vice, text string) error {
func Sealf(err error, v Vice, format string, a ...interface{}) error {
return skip.Sealf(err, skip.Vice(v), 1, format, a...)
}

// ForError returns a wrapped vice type found for the given error.
//
// This loops over all types to determine if the the error wraps that type. This
// means this function is not deterministic if multiple `Wrap()` calls have been
// used on the given error. To make sure it is deterministic, use the `Seal()`
// method.
//
// If the error is not wrapped or sealed with this package, it will return
// NoVice.
//
// This can be useful for map lookups to map specific types to descriptive
// messages.
func ForError(err error) Vice {
for _, v := range vices {
if Is(err, v) {
return v
}
}

return NoVice
}
19 changes: 19 additions & 0 deletions error_test.go
@@ -0,0 +1,19 @@
package vice

import (
"errors"
"testing"
)

func TestForError(t *testing.T) {
for _, v := range vices {
err := New(v, "test error")
if v != ForError(err) {
t.Fatalf("expected vice from error to equal error's specified vice")
}
}

if ForError(errors.New("non vice error")) != NoVice {
t.Fatalf("expected non vice error to return NoVice type")
}
}
2 changes: 1 addition & 1 deletion go.mod
Expand Up @@ -2,4 +2,4 @@ module github.com/jbowes/vice

go 1.12

require golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522
require golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543
4 changes: 2 additions & 2 deletions go.sum
@@ -1,2 +1,2 @@
golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522 h1:bhOzK9QyoD0ogCnFro1m2mz41+Ib0oOhfJnBp5MR4K4=
golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

0 comments on commit a9ee44d

Please sign in to comment.