Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions common/errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ func (err *Error) Inner() error {
return err.inner
}

// Unwrap implements the standard library's errors.Unwrap contract, allowing
// errors.Is and errors.As to traverse to the underlying error.
func (err *Error) Unwrap() error {
return err.inner
}

func (err *Error) Base(e error) *Error {
err.inner = e
return err
Expand Down
51 changes: 51 additions & 0 deletions common/errors/errors_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package errors_test

import (
stderrors "errors"
"io"
"strings"
"syscall"
"testing"

"github.com/google/go-cmp/cmp"
Expand Down Expand Up @@ -60,3 +62,52 @@ func TestErrorMessage(t *testing.T) {
}
}
}

var errUnwrapSentinel = stderrors.New("unwrap sentinel")

type typedUnwrapErr struct{ code int }

func (typedUnwrapErr) Error() string { return "typed unwrap error" }

func TestErrorUnwrap(t *testing.T) {
expected := stderrors.New("base")
if actual := stderrors.Unwrap(New("wrapper").Base(expected)); actual != expected {
t.Errorf("Unwrap() = %v, expected the wrapped base error", actual)
}
if actual := stderrors.Unwrap(New("no inner")); actual != nil {
t.Errorf("Unwrap() = %v, expected nil", actual)
}
}

func TestErrorIsThroughChain(t *testing.T) {
chain := New("a").Base(New("b").Base(New("c").Base(errUnwrapSentinel)))
if !stderrors.Is(chain, errUnwrapSentinel) {
t.Errorf("errors.Is could not find the sentinel through the *Error chain: %v", chain)
}
}

func TestErrorAsThroughChain(t *testing.T) {
chain := New("outer").Base(New("inner").Base(typedUnwrapErr{code: 42}))
var actual typedUnwrapErr
if !stderrors.As(chain, &actual) {
t.Fatalf("errors.As could not extract typedUnwrapErr through the *Error chain: %v", chain)
}
if actual.code != 42 {
t.Errorf("extracted code = %d, expected 42", actual.code)
}
}

// The motivating case: recover a syscall.Errno from a multi-layer wrap.
func TestErrorAsSyscallErrno(t *testing.T) {
const expected = syscall.Errno(4242)
chain := New("failed to listen TCP on 443").Base(
New("failed to listen on address: 0.0.0.0:443").Base(
New("failed to listen TCP on 0.0.0.0:443").Base(expected)))
var actual syscall.Errno
if !stderrors.As(chain, &actual) {
t.Fatalf("errors.As could not extract syscall.Errno through the *Error chain: %v", chain)
}
if actual != expected {
t.Errorf("extracted errno = %d, expected %d", actual, expected)
}
}