how can i get the error code "os.ErrNotExist" from the error itself?

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

how can i get the error code "os.ErrNotExist" from the error itself?

问题

这段代码可以在这里运行:https://play.golang.org/p/dX6dOzWS-Gx

cachedirstring := "./cache"
_, err = os.Stat(cachedirstring)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
fmt.Printf("%T\n", err)
}
os.Exit(1)
}

这段代码的输出是:

*fs.PathError

我知道从一本书中可以使用errors.Is(err, os.ErrNotExist)。我的问题是,我如何知道errors.Is(err, os.ErrNotExist)会返回true(通过代码而不是搜索引擎)?

我如何找到所有与err相等的目标错误?

英文:

This code can be run here: https://play.golang.org/p/dX6dOzWS-Gx

cachedirstring := "./cache"
_, err = os.Stat(cachedirstring)
if err != nil {
	if errors.Is(err, os.ErrNotExist) {
		fmt.Printf("%T\n", err)
	}
	os.Exit(1)
}

This outputs:

*fs.PathError

I know to use errors.Is(err, os.ErrNotExist) from a book. My question is, how could I know that errors.Is(err, os.ErrNotExist) would return true (through code, rather than a search engine) ?

How can I find all target errors that would equal err ?

答案1

得分: 2

你可以在“纸上”模拟 errors.Is 的行为:

  • 当调用 errors.Unwrap 方法时,检查循环遍历错误链会发生什么。
  • 对于每个错误,考虑它是否与目标相等(使用==),或者它是否实现了 Is(error) bool 方法并且会返回 true。

例如,如果 syscall.Errno 类型具有正确的错误代码,那么这一行会使 errors.Is(..., os.ErrNoExist) 返回 true。

英文:

You can certainly emulate what errors.Is does "on paper":

  • Check what looping through the chain of errors would do, when the erros.Unwrap method is called on it.
  • For each error, consider whether it is == to the target, or if it implements the Is(error) bool method and would return true for it.

For example, this line makes errors.Is(..., os.ErrNoExist) true for the syscall.Errno type if it has the right error code.

huangapple
  • 本文由 发表于 2021年8月6日 14:22:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/68677030.html
匿名

发表评论

匿名网友

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

确定