如何捕捉特定的错误 [英] How to `catch` specific errors

查看:101
本文介绍了如何捕捉特定的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我使用一个Go标准库函数,例如:

For example, I am using one Go standard library function as:

func Dial(network, address string) (*Client, error)

此函数可能返回错误,我只关心报告连接丢失的错误或连接被拒绝,然后执行一些代码来解决这些问题。

似乎是:

This function may return errors, and I just care about errors which report "connection lost" or "connection refused", then do some code to fix these.
It seems like:

client, err := rpc.Dial("tcp", ":1234")  
if err == KindOf(ConnectionRefused) {
  // do something
}

此外,如何获取特定标准库函数可能返回的所有错误?

What's more, how to get all the errors a specific standard library function may return?

推荐答案

没有标准方法可以做到这一点。

There's no standard way to do this.

最明显的方法,只有在没有此方法时才应使用另一个可用的方法是将错误字符串与您的期望进行比较:

The most obvious way, which should only be used if no other method is available, is to compare the error string against what you expect:

if err.Error() == "connection lost" { ... }

在某些情况下可能更强大:

Or perhaps more robust in some situations:

if strings.HasSuffix(err.Error(), ": connection lost") { ... }

但是许多库将返回特定的错误类型,这使此操作变得更加容易。

But many libraries will return specific error types, which makes this much easier.

与您有关的是 net 导出的各种错误类型。 code> 包: AddrError DNSConfigError DNSError 错误,等等。

In your case, what's relevant are the various error types exported by the net package: AddrError, DNSConfigError, DNSError, Error, etc.

您可能最关心 net.Error ,它用于网络错误。因此,您可以这样检查:

You probably care most about net.Error, which is used for network errors. So you could check thusly:

if _, ok := err.(net.Error); ok {
    // You know it's a net.Error instance
    if err.Error() == "connection lost" { ... }
}




此外,如何获取特定标准库函数可能返回的所有错误?

What's more, how to get all the errors a specific standard library function may return?

唯一做到这一点的简单方法是读取库的源代码。在走向极端之前,第一步就是简单地阅读godoc,就像 net 包的情况一样,错误已得到很好的记录。

The only fool-proof way to do this is to read the source for the library. Before going to that extreme, a first step is simply to read the godoc, as in the case of the net package, the errors are pretty well documented.

这篇关于如何捕捉特定的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆