mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
fix: avoid emitting version warning when connection error encountered (#3082)
This commit is contained in:
@@ -1,5 +1,11 @@
|
||||
package codersdk
|
||||
|
||||
import (
|
||||
"net"
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
)
|
||||
|
||||
// Response represents a generic HTTP response.
|
||||
type Response struct {
|
||||
// Message is an actionable message that depicts actions the request took.
|
||||
@@ -25,3 +31,16 @@ type ValidationError struct {
|
||||
Field string `json:"field" validate:"required"`
|
||||
Detail string `json:"detail" validate:"required"`
|
||||
}
|
||||
|
||||
// IsConnectionErr is a convenience function for checking if the source of an
|
||||
// error is due to a 'connection refused', 'no such host', etc.
|
||||
func IsConnectionErr(err error) bool {
|
||||
var (
|
||||
// E.g. no such host
|
||||
dnsErr *net.DNSError
|
||||
// Eg. connection refused
|
||||
opErr *net.OpError
|
||||
)
|
||||
|
||||
return xerrors.As(err, &dnsErr) || xerrors.As(err, &opErr)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package codersdk_test
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/codersdk"
|
||||
)
|
||||
|
||||
func TestIsConnectionErr(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
type tc = struct {
|
||||
name string
|
||||
err error
|
||||
expectedResult bool
|
||||
}
|
||||
|
||||
cases := []tc{
|
||||
{
|
||||
// E.g. "no such host"
|
||||
name: "DNSError",
|
||||
err: &net.DNSError{
|
||||
Err: "no such host",
|
||||
Name: "foofoo",
|
||||
Server: "1.1.1.1:53",
|
||||
IsTimeout: false,
|
||||
IsTemporary: false,
|
||||
IsNotFound: true,
|
||||
},
|
||||
expectedResult: true,
|
||||
},
|
||||
{
|
||||
// E.g. "connection refused"
|
||||
name: "OpErr",
|
||||
err: &net.OpError{
|
||||
Op: "dial",
|
||||
Net: "tcp",
|
||||
Source: nil,
|
||||
Addr: nil,
|
||||
Err: &os.SyscallError{},
|
||||
},
|
||||
expectedResult: true,
|
||||
},
|
||||
{
|
||||
name: "OpaqueError",
|
||||
err: xerrors.Errorf("I'm opaque!"),
|
||||
expectedResult: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
c := c
|
||||
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
require.Equal(t, c.expectedResult, codersdk.IsConnectionErr(c.err))
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user