英文:
golang idiomatic way to detect no such host error
问题
我正在使用这段代码,但感觉不太对:
if err, ok := err.(net.Error); ok {
	var message string
	if err.Timeout() {
		message = "Timeout"
	} else if strings.HasSuffix(err.Error(), "no such host") {
		message = "No such host"
	}
}
有没有更符合惯用方式的方法?
英文:
I am using this but it doesn't feel right:
if err, ok := err.(net.Error); ok {
	var message string
	if err.Timeout() {
		message = "Timeout"
	} else if strings.HasSuffix(err.Error(), "no such host") {
		message = "No such host"
	}
}
Is there a more idiomatic way?
答案1
得分: 4
根据Go 1.13版本的文档,你可以使用errors.As或errors.Is来检查DNS错误。
import (
	"errors"
	"fmt"
	"net"
)
func main() {
	var dnsError *net.DNSError
	if errors.As(err, &dnsError) {
		fmt.Println("DNS错误", dnsError)
	}
}
原始答案中的代码可以用来检查DNS错误。例如,如果err是我们的错误:
if err, ok := err.(*url.Error); ok {
	if err, ok := err.Err.(*net.OpError); ok {
		if _, ok := err.Err.(*net.DNSError); ok {
			retry(r)
		}
	}
}
英文:
As Of Go 1.13:
You can use errors.As, OR errors.Is
var dnsError *net.DNSError
if errors.As(err, &dnsError) {
	fmt.Println("DNS Error", dnsError)
}
Original Answer:
You can check DNS errors with this code. For example if err is our error:
if err, ok := err.(*url.Error); ok {
	if err, ok := err.Err.(*net.OpError); ok {
		if _, ok := err.Err.(*net.DNSError); ok {
			retry(r)
		}
	}
}
答案2
得分: 3
我认为你可以使用DNSError类型来替代普通的Error。
err, ok := err.(net.DNSError)
				通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论