英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论