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)
var hErr HTTPError
var vizErr vizerror.Error
var hErrOK bool
if errors.As(err, &hErr) {
hErrOK = true
} else if errors.As(err, &vizErr) {
} else if vizErr, ok := vizerror.As(err); ok {
hErrOK = true
hErr = HTTPError{Msg: vizErr.Error()}
}

@ -42,3 +42,9 @@ func Wrap(err error) error {
}
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 (
"errors"
"fmt"
"io/fs"
"testing"
)
@ -28,3 +29,16 @@ func TestErrorf(t *testing.T) {
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