util/vizerror: add As function to get wrapped Error

Signed-off-by: Will Norris <will@tailscale.com>
pull/7155/head
Will Norris 2 years ago committed by Will Norris
parent 51e1ab5560
commit 10085063fb

@ -266,11 +266,10 @@ func (h retHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := h.rh.ServeHTTPReturn(lw, r) err := h.rh.ServeHTTPReturn(lw, r)
var hErr HTTPError var hErr HTTPError
var vizErr vizerror.Error
var hErrOK bool var hErrOK bool
if errors.As(err, &hErr) { if errors.As(err, &hErr) {
hErrOK = true hErrOK = true
} else if errors.As(err, &vizErr) { } else if vizErr, ok := vizerror.As(err); ok {
hErrOK = true hErrOK = true
hErr = HTTPError{Msg: vizErr.Error()} hErr = HTTPError{Msg: vizErr.Error()}
} }

@ -42,3 +42,9 @@ func Wrap(err error) error {
} }
return Error{err} return Error{err}
} }
// As returns the first vizerror.Error in err's chain.
func As(err error) (e Error, ok bool) {
ok = errors.As(err, &e)
return
}

@ -5,6 +5,7 @@ package vizerror
import ( import (
"errors" "errors"
"fmt"
"io/fs" "io/fs"
"testing" "testing"
) )
@ -28,3 +29,16 @@ func TestErrorf(t *testing.T) {
t.Errorf("error chain does not contain fs.ErrNotExist") t.Errorf("error chain does not contain fs.ErrNotExist")
} }
} }
func TestAs(t *testing.T) {
verr := New("visible error")
err := fmt.Errorf("wrap: %w", verr)
got, ok := As(err)
if !ok {
t.Errorf("As() return false, want true")
}
if got != verr {
t.Errorf("As() returned error %v, want %v", got, verr)
}
}

Loading…
Cancel
Save