drc15469 2014-06-04 17:26
浏览 21
已采纳

调用后获取操作系统错误的惯用方式

If I do

s, err := os.Stat(path)

and err != nil I need to know if the file doesn't exist vs I don't have permission to access it, etc. How do I get the underlying error code? Reading the os package docs it seems to suggest that I read the text of the error string - surely not?

  • 写回答

1条回答 默认 最新

  • dongsou4301 2014-06-04 17:51
    关注

    What FUZxxl says.

    From the os.Stat documentation:

    Stat returns a FileInfo describing the named file. If there is an error, it will be of type *PathError.

    PathError is documented on the same page, stating that it holds the operation that caused the error, the path to the file that caused it and the underlying system's error. In case the file was not found when calling os.Stat, the returned error would be something like this:

    &PathError{"stat", "/your/file", syscall.Errno(2)}
    

    Since the underlying error is inherently depending on the OS you use, the only thing that you can do is to understand PathError.Err. For UNIX systems the syscall package has the Errno error type returned by syscalls like syscall.Stat. You can compare this value with the constants in the syscall package and handle the error (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")
        }
    }
    

    The shorter way of doing this is to use os.IsNotExist which does pretty much the above and is, most importantly, platform independent:

    stat, err := os.Stat(file)
    
    if err != nil && os.IsNotExist(err) {
        // ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?