doty58493 2014-05-04 03:04
浏览 485
已采纳

如何检查ioutil.ReadFile返回的错误中的特定类型的错误?

When I use ioutil to read a file, it may return an error. But if I want to filter some error code, what should I do?

res, err := ioutil.ReadFile("xxx")
if err != nil {
    fmt.Println(err.Error())  
}
...

In the code snippet above, when a file has no permission, fmt.Println(err.Error()) will print "open xxxxx: permission denied. If I want to capture this kind error, how can I know that file read failed because permission was denied?

Should I search err.Error() for the string permission denied - this looks ungraceful. Is there any better way?

Thanks in advance.

Update

After trying @Intermernet solution, I found that it will not hit case os.ErrPermission, it will hit default and print "open xxx: Permission denied".

@Aedolon solution is ok, os.IsPermission(err) can tell that a file has failed with permission deny.

  • 写回答

2条回答 默认 最新

  • dp926460 2014-05-04 04:34
    关注

    According to the current API, ioutil.ReadFile doesn't guarantee any specific behaviour except that it will return err == nil when successful. Even the syscall package doesn't actually guarantee a specific error.

    The current implementation of ioutil.ReadFile uses os.Open, which will return *os.PathError when failing to open a file, not os.ErrPermission or anything else. os.PathError contains a field Err which is also an error - in this case, a syscall.Errno. The string "permission denied" is produced from a private table of error messages and it's both architecture and implementation-specific. In my Windows machine it says "Access is denied" instead.

    AFAIK, the correct method is to use os.IsPermission(err), which will return true in case of lacking permissions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效