英文:
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 <default val>, 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 <blah>: 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
> func IsNotExist(err error) bool
>
>
> 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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论