go - 调用后获取操作系统错误的惯用方法

标签 go

如果我这样做

s, err := os.Stat(path)

err != nil 我需要知道该文件是否不存在或者我没有权限访问它,等等。如何获取底层错误代码?阅读 os 包文档似乎建议我阅读错误字符串的文本 - 肯定不是吗?

最佳答案

什么 FUZxxl says .

来自os.Stat documentation :

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/

相关文章:

go - 即时更改序列化的 protobuf 消息?

c - 使用 Go 和 OpenCV 读取/写入图像中的 ICC 配置文件

go - 为什么没有检测到 Go?

go - Go Lang ioutil.writeFile函数使目录和文件只读

go - Go中for循环中的多个变量

unit-testing - 如何在 Go 中获得所有包的代码覆盖率?

go - 如何加载和缓存 100 页模板,并呈现正确的模板并在处理程序中返回

转到数组元素的地址

c - 使用CGO将Go嵌套结构的数组转换为C?

serialization - golang stringize struct 结构(没有数据)