具体检查超时错误

问题描述 投票:24回答:3

我在调用webservice时使用以下内容检查超时,但我想特别检查是否返回了超时错误。我该怎么做:S

我有这个:

// Timeout
type Timeout struct {
    Connect   time.Duration
    ReadWrite time.Duration
}

// TimeoutDialer
func TimeoutDialer(timeout *Timeout) func(net, addr string) (c net.Conn, err error) {
    return func(netw, addr string) (net.Conn, error) {    
        conn, err := net.DialTimeout(netw, addr, timeout.Connect)
        if err != nil {
            return nil, err
        }
        conn.SetDeadline(time.Now().Add(timeout.ReadWrite))
        return conn, nil
    }
}

// HttpClient
func HttpClient(config Config) *http.Client {
    to := &Timeout{
        Connect:   time.Duration(config.MaxWait) * time.Second,
        ReadWrite: time.Duration(config.MaxWait) * time.Second,
    }

    return &http.Client{
        Transport: &http.Transport{
            Dial: TimeoutDialer(to),
        },
    }
}
go
3个回答
56
投票

从go1.6开始,所有来自超时的错误都应符合net.Error并正确设置Timeout()。您需要检查的是:

if err, ok := err.(net.Error); ok && err.Timeout() {

在旧版本中,通过http包检查超时更加困难。

  • 如果您在底层连接上设置截止日期,则可以使用Timeout()获取*net.OpError
  • 您可以获得实现tlsHandshakeTimeoutError接口的net.Error(显然不会导出)。
  • 如果url包中存在问题(初始连接期间超时),您可以获得url.Error
  • 如果使用http.Client.Timeout [go1.3 +](调用Transport.CancelRequest)设置了超时设置,则可能会出现“使用封闭网络连接”的错误。从go1.5开始,这将正确设置Timeout属性。

您可以使用类型开关检查net.Error

switch err := err.(type) {
case net.Error:
    if err.Timeout() {
        fmt.Println("This was a net.Error with a Timeout")
    }
case *url.Error:
    fmt.Println("This is a *url.Error")
    if err, ok := err.Err.(net.Error); ok && err.Timeout() {
        fmt.Println("and it was because of a timeout")
    }
}

使用go <1.5,您需要检查http.Client超时的错误字符串:

if err != nil && strings.Contains(err.Error(), "use of closed network connection") {
    fmt.Println("Could be from a Transport.CancelRequest")
}

14
投票

你想要net.Error界面。 http://golang.org/pkg/net/#Error

if e,ok := err.(net.Error); ok && e.Timeout() {
    // This was a timeout
} else if err != nil {
    // This was an error, but not a timeout
}

请注意,类型断言err.(net.Error)将正确处理nil情况,如果ok作为错误返回,则nil值返回false,使Timeout检查短路。


1
投票

您可以简单地将错误传递给os.IsTimeout(),如果它是net / http返回的超时,则它将返回true。

func IsTimeout(err error) bool

IsTimeout返回一个布尔值,指示是否已知错误报告超时发生。

© www.soinside.com 2019 - 2024. All rights reserved.