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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化