如何处理”os.Stat中的”no such file or directory”错误?

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

How to handle "no such file or directory" in os.Stat

问题

我有一段代码,它在查找文件的时候会使用stat函数,并在文件不存在时返回一些默认值。具体来说,代码大致如下:

fileInfo, err := os.Stat(absolutePath)
if err != nil {
	if os.IsNotExist(err) {
		return <默认值>, nil
	}
	return nil, fmt.Errorf(...)
}

为了"捕获"文件不存在的错误,我了解到建议使用os.IsNotExist来检查错误是否表示文件不存在。然而,os.IsNotExist并不能捕获这个错误,因为平台返回的错误信息是open <blah>: no such file or directory。我可以在这里添加自己的错误处理,但是否有一种惯用的方式来处理os调用中的"文件不存在"错误?似乎os.IsNotExist检查处理的错误只是一种特殊情况,只针对一种可能的"文件不存在"错误类型。

英文:

I have a piece of code that is looking to stat a file and return some default values if the file does not exist. Namely, the piece of code looks something like the following:

fileInfo, err := os.Stat(absolutePath)
if err != nil {
	if os.IsNotExist(err) {
		return &lt;default val&gt;, nil
	}
	return nil, fmt.Errorf(...)
}

To "catch" the "file does not exist" error I have read that it's advised to use os.IsNotExist to check if the error indicates the file does not exist. However, os.IsNotExist does not catch this error since the platform returns open &lt;blah&gt;: no such file or directory. I can add my own error handling here but is there is an idiomatic way to handle "file does not exist" errors from os calls? It seems like the error handled by the os.IsNotExist check is special cased to just one type of potential "file does not exist" error.

答案1

得分: 4

如果你阅读文档,你会看到以下内容:

func IsNotExist

func IsNotExist(err error) bool

IsNotExist 返回一个布尔值,指示错误是否表示文件或目录不存在。它适用于 ErrNotExist 和一些 syscall 错误。

这个函数早于 errors.Is。它只支持由 os 包返回的错误。
新代码应该使用 errors.Is(err, fs.ErrNotExist)。[强调. 我的]

英文:

If you read the documentation, you'll see this:

> func IsNotExist
> go
&gt; func IsNotExist(err error) bool
&gt;

>
> IsNotExist returns a boolean indicating whether the error is known to
> report that a file or directory does not exist. It is satisfied by
> ErrNotExist as well as some syscall errors.
>
> This function predates errors.Is. It only supports errors returned by the os package.
> New code should use errors.Is(err, fs.ErrNotExist). [emph. mine]

huangapple
  • 本文由 发表于 2023年1月25日 06:38:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75228004.html
匿名

发表评论

匿名网友

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

确定