dongyan3237 2018-08-07 23:55
浏览 110

检查来自os.Remove的错误消息

What's the most idiomatic way to check error messages? My use case is that in err := os.Remove(path), I consider a success either:

A) if err == nil

or

B) if err != nil but the error is thrown because the file was not found.

any other error should cause the removal to retry. Currently I've wrapped this in a for { ... } loop and am checking:

if err == nil || strings.Contains(err.Error(), "no such file") {
    // Success
} else {
    // Fail
}

Since the docs say:

If there is an error, it will be of type *PathError.

I don't think there's a way to check by type assertion. Am I missing something fundamental? My error handling in Go has always felt somewhat slapdash.

  • 写回答

2条回答 默认 最新

  • doushi1912 2018-08-08 14:04
    关注

    The "type" error is an interface. Interfaces don't have an concrete type. To get the type of the value you could use a type assertion or a type switch:

    // Type assertion
    _, ok := err.(*PathError)
    
    // Type switch
    switch err.(type) {
    case *PathError:
        // You know the type now
    }
    

    This is an idiomatic way to find out of which type an error is. As in the comments specified there is already a function inside the os package which does this for you (https://golang.org/pkg/os/#IsNotExist)

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么