Skip to content

Commit 13cf585

Browse files
committed
exhttp: Add IsNetworkError helper
1 parent 05fea40 commit 13cf585

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

exhttp/networkerror.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// Copyright (c) 2025 Tulir Asokan
2+
//
3+
// This Source Code Form is subject to the terms of the Mozilla Public
4+
// License, v. 2.0. If a copy of the MPL was not distributed with this
5+
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6+
7+
package exhttp
8+
9+
import (
10+
"errors"
11+
"net"
12+
"syscall"
13+
14+
"golang.org/x/net/http2"
15+
)
16+
17+
func IsNetworkError(err error) bool {
18+
for err != nil {
19+
if _, ok := err.(net.Error); ok {
20+
return true
21+
} else if _, ok := err.(*net.OpError); ok {
22+
return true
23+
} else if errno, ok := err.(syscall.Errno); ok {
24+
// common errnos for network related operations
25+
return errno == syscall.ENETDOWN ||
26+
errno == syscall.ENETUNREACH ||
27+
errno == syscall.ENETRESET ||
28+
errno == syscall.ECONNABORTED ||
29+
errno == syscall.ECONNRESET ||
30+
errno == syscall.ENOBUFS ||
31+
errno == syscall.ETIMEDOUT ||
32+
errno == syscall.ECONNREFUSED ||
33+
errno == syscall.EHOSTDOWN ||
34+
errno == syscall.EHOSTUNREACH
35+
} else if errors.As(err, &http2.StreamError{}); ok {
36+
return true
37+
}
38+
39+
err = errors.Unwrap(err)
40+
}
41+
42+
return false
43+
}

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ require (
1111
github.com/rs/zerolog v1.34.0
1212
github.com/stretchr/testify v1.10.0
1313
golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6
14+
golang.org/x/net v0.40.0
1415
golang.org/x/sys v0.33.0
1516
golang.org/x/text v0.25.0
1617
google.golang.org/protobuf v1.36.6

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOf
2727
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
2828
golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6 h1:y5zboxd6LQAqYIhHnB48p0ByQ/GnQx2BE33L8BOHQkI=
2929
golang.org/x/exp v0.0.0-20250506013437-ce4c2cf36ca6/go.mod h1:U6Lno4MTRCDY+Ba7aCcauB9T60gsv5s4ralQzP72ZoQ=
30+
golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY=
31+
golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds=
3032
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
3133
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
3234
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=

0 commit comments

Comments
 (0)