如果我这样做
s, err := os.Stat(path)
和 err != nil
我需要知道该文件是否不存在或者我没有权限访问它,等等。如何获取底层错误代码?阅读 os
包文档似乎建议我阅读错误字符串的文本 - 肯定不是吗?
最佳答案
什么 FUZxxl says .
Stat returns a
FileInfo
describing the named file. If there is an error, it will be of type*PathError
.
PathError
已记录 on the same page ,声明它包含导致错误的操作、导致错误的文件路径以及底层系统的错误。如果在调用 os.Stat
时找不到文件,返回的错误将是这样的:
&PathError{"stat", "/your/file", syscall.Errno(2)}
由于潜在的错误本质上取决于您使用的操作系统,您唯一能做的就是
理解 PathError.Err
。对于 UNIX 系统,syscall
包具有 Errno
error type由系统调用返回,如 syscall.Stat
。您可以将此值与 constants in the syscall
package 进行比较并处理错误(Click to play):
stat, err := os.Stat(file)
if perr, ok := err.(*os.PathError); ok {
switch perr.Err.(syscall.Errno) {
case syscall.ENOENT: fmt.Println("No such file or directory.")
default: panic("Unknown error")
}
}
执行此操作的较短方法是使用 os.IsNotExist
哪个pretty much the above
最重要的是,平台独立:
stat, err := os.Stat(file)
if err != nil && os.IsNotExist(err) {
// ...
}
关于go - 调用后获取操作系统错误的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24043781/