golang idiomatic way to detect no such host error

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

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.Aserrors.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)
英文:

I think you can use DNSError type instead of common Error.

err, ok := err.(net.DNSError)

huangapple
  • 本文由 发表于 2017年1月16日 12:31:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/41669475.html
匿名

发表评论

匿名网友

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

确定