duanluwei9374 2016-03-13 11:55
浏览 31
已采纳

如何检查恢复中错误的确切类型?

I'm following this example here:

https://www.socketloop.com/tutorials/golang-smarter-error-handling-with-strings-contains-function

 if !strings.Contains(err.Error(), "timed out") {
    fmt.Printf("resulting error not a timeout: %s", err)
 }

However, if I do that in my code I will get this

err.Error undefined (type interface {} is interface with no methods)

I wonder what I'm doing wrong here, and how should I check for an exact error (in my case I want to recover from the error "slice bounds out of range")

Best,

  • 写回答

1条回答 默认 最新

  • douchui3933 2016-03-13 12:10
    关注

    Use type assertion to get error https://play.golang.org/p/BryV7YfZHS

    defer func(){
        err := recover().(error)
        fmt.Println(err.Error())
    }()
    
    a := make([]int, 0)
    a[1] = 0
    

    But I suggest you don't do that. First, you should not use recover. In almost all cases that means you're doing something wrong. Instead, fix the code that panics.

    Second, don't use string matching to determine the cause of the error. There're many reasons why it's bad but I will just say that it's not the Go way of doing things. I understand that you may be using API that just doesn't leave you a choice but try to find a better way. Use type assertion, type switch to get the exact error type and go from there.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题