Skip to content

Commit

Permalink
[xerrors] implement IsTimeout helper function (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
kucherenkovova authored Jan 4, 2025
1 parent 7a4dfc3 commit 09374b3
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 1 deletion.
3 changes: 2 additions & 1 deletion go.work
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
go 1.22.2
go 1.23.4

use (
./xerrors
./xmaps
./xmath
./xnet/xhttp
Expand Down
21 changes: 21 additions & 0 deletions xerrors/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package xerrors

import (
"errors"
)

// IsTimeout reports whether the provided error indicates a timeout condition.
func IsTimeout(err error) bool {
if err == nil {
return false
}

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

inner := errors.Unwrap(err)

return inner != nil && IsTimeout(inner)
}
35 changes: 35 additions & 0 deletions xerrors/errors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package xerrors_test

import (
"context"
"fmt"
"testing"

"github.com/kucherenkovova/gopypaste/xerrors"
)

type customTimeoutError struct{}

func (e customTimeoutError) Error() string { return "timeout" }

func (e customTimeoutError) Timeout() bool { return true }

func TestIsTimeout(t *testing.T) {
tests := []struct {
name string
err error
want bool
}{
{name: "nil", err: nil, want: false},
{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},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := xerrors.IsTimeout(tt.err); got != tt.want {
t.Errorf("IsTimeout() = %v, want %v", got, tt.want)
}
})
}
}
3 changes: 3 additions & 0 deletions xerrors/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/kucherenkovova/gopypaste/xerrors

go 1.23.4

0 comments on commit 09374b3

Please sign in to comment.