douyinmian8151 2018-05-31 23:53
浏览 202
已采纳

Golang错误和说明文件

Unfortunately golang error documentation in the standard library is next to non-existent. e.g. just opening a file, the return values for the error are not documented except that you can print a string. But this is not always the right way to handle it.

Is there a way to determine what the real error code might be through trial and error rather than just printing out the text? It seems silly to match the whole text for the specific error.

e.g. given I want to ultimately achieve something like this (assuming it's right)

if fd, err := io.Open("filename"); err != nil {
  if err != io.ErrFileNotFound {
    log.Fatalf("Error opening file: %s", err)
  }
}

As far as I can tell anything that implements the error interface will be able to be used as an error. But determining what the error is is what I'm struggling with. The error may be a struct that has other fields in it like a number field to tell me what type of error it is aside from the text itself. But how would I know what other data the error contains short of looking through many source files and sometimes tens of function calls.

Does this make sense?

As a more practical example. I am using a yaml library to load a config file. If the config file doesn't exist I want to carry on (it'll use defaults). But if there is a permissions error I want the error to be treated as fatal. The problem is, it's not entirely clear what the error will look like ahead of time.

  • 写回答

2条回答 默认 最新

  • douzi2778 2018-06-01 00:09
    关注

    Use os.IsNotExist to check for file not found errors:

    f, err := os.Open("filename")
    if os.IsNotExist(err) {
      // handle missing file
    } else if err != nil {
      // handle other errors
    }
    

    The functions os.IsExist, os.IsPermission and is.Timeout check for other common types of errors.

    The os, io and other packages declare variables for specific errors.

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

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?