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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度