Skip to content

Commit

Permalink
[xerrors] support joined errors in IsTimeout function
Browse files Browse the repository at this point in the history
  • Loading branch information
kucherenkovova committed Jan 4, 2025
1 parent 724f547 commit a97914e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
8 changes: 6 additions & 2 deletions xerrors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package xerrors

import (
"errors"
"slices"
)

// IsTimeout reports whether the provided error indicates a timeout condition.
Expand All @@ -10,11 +11,14 @@ func IsTimeout(err error) bool {
return false
}

e, ok := err.(interface{ Timeout() bool })
if ok && e.Timeout() {
if te, ok := err.(interface{ Timeout() bool }); ok && te.Timeout() {
return true
}

if joined, ok := err.(interface{ Unwrap() []error }); ok {
return slices.ContainsFunc(joined.Unwrap(), IsTimeout)
}

inner := errors.Unwrap(err)

return inner != nil && IsTimeout(inner)
Expand Down
3 changes: 3 additions & 0 deletions xerrors/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package xerrors_test

import (
"context"
"errors"
"fmt"
"testing"

Expand All @@ -24,6 +25,8 @@ func TestIsTimeout(t *testing.T) {
{name: "context timeout", err: context.DeadlineExceeded, want: true},
{name: "wrapped context timeout", err: fmt.Errorf("bad stuff: %w", context.DeadlineExceeded), want: true},
{name: "custom timeout", err: customTimeoutError{}, want: true},
{name: "joined errors", err: errors.Join(errors.New("oops"), context.DeadlineExceeded), want: true},
{name: "joined errors - no timeout", err: errors.Join(errors.New("oops"), errors.New("ididitagain")), want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit a97914e

Please sign in to comment.