How to check if error is tls handshake timeout in Go

huangapple go评论104阅读模式
英文:

How to check if error is tls handshake timeout in Go

问题

我有以下代码向URL发出请求并检查错误。

import "net/http"

response, err := http.Head("url")

如何检查错误是否是由于TLS握手超时引起的?我尝试了以下代码:

if err != nil {
    tlsError, ok := err.(http.tlsHandshakeTimeoutError)
    if ok {
        // 处理错误
    }
}

但是我无法访问http.tlsHandshakeTimeoutError类型,因为它是未导出的。在Go中,还有其他方法可以检查错误类型吗?

英文:

I have the following code making a request to URL and checking for errors.

import "net/http"

response, err := http.Head("url")

How do check if the error is due to tls handshake timeout? I tried the following:

if err != nil {
    tlsError, ok := err.(http.tlsHandshakeTimeoutError)
    if ok {
        // handle the error
    }
}

But I cannot access the http.tlsHandshakeTimeoutError type because it is unexported. How else can I check for the error type in go?

答案1

得分: 3

是的,tlsHandshakeTimeoutError - 没有被导出,检查这个错误的唯一可能性是:

import "net/url"

// ....

if urlError, ok := err.(*url.Error); ok {
    if urlError.Error() == "net/http: TLS handshake timeout" {
        // 处理错误
    }
}

这里有一个关于此问题的开放讨论:

https://github.com/golang/go/issues/15935

顺便说一下,http 错误(包括 tlsHandshakeTimeoutError)还提供了:

type WithTimeout interface {
   Timeout() bool
}

如果你不喜欢字符串比较,你可以使用它来进行检查。这里 是来自 http2 包的 isTemporary 实现示例。

英文:

Yes tlsHandshakeTimeoutError - is not exported and the only one
possibility to check on this error is:

import "net/url"

// ....

if urlError,ok :=  err.(*url.Error)  ; ok {
    if urlError.Error() == "net/http: TLS handshake timeout" {
        // handle the error
    }
}

Here is open ticket with discussion about it:

https://github.com/golang/go/issues/15935

By the way http errors (and tlsHandshakeTimeoutError also) provide also:

type WithTimeout interface {
   Timeout() bool
}

You can use it for you check if you don't like string comparsion. Here is example of isTemporary implementation from http2 package.

huangapple
  • 本文由 发表于 2017年8月21日 17:11:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/45793299.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定