util/vizerror: add As function to get wrapped Error

Signed-off-by: Will Norris <will@tailscale.com>
This commit is contained in:
Will Norris 2023-02-01 14:07:24 -08:00 committed by Will Norris
parent 51e1ab5560
commit 10085063fb
3 changed files with 21 additions and 2 deletions

View File

@ -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()}
}

View File

@ -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
}

View File

@ -5,6 +5,7 @@
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)
}
}