dsiftnc99059 2017-11-30 22:27
浏览 12
已采纳

如何使用错误界面

I have source like the following:

type Record struct {
    Message string `json:"message"`
    Service string `json:"service"`
    Success bool   `json:"success"`
    Error   string `json:"error"`
}

func (zp *Zephyr) Write(err ...*error) {

    if len(err) > 0 {
        errPtr := err[0]
        if errPtr != nil && *errPtr != nil {
            // error occurred, set success to false and Error to the error message
            zp.Success = false
            zp.Error = errPtr
        } else {
            zp.Success = true
        }
    }
}

What I don't understand is how can I access the string that is embedded in errPtr?

  • 写回答

1条回答 默认 最新

  • dougou1127 2017-11-30 22:30
    关注

    First, you likely don't want *error, you most likely just want error; pointers to interfaces are very seldom the correct choice.

    Second, there isn't necessarily a string embedded in an error. The definition of error is nothing more than:

    type error interface {
            Error() string
    }
    

    Meaning if you call the Error() method, it will return a string, but it may be generated every time the method is called; it's not necessarily a string field in the error object.

    Most likely, what you want is something like this:

    func (zp *Zephyr) Write(err ...error) {
    
        if len(err) > 0 {
            errPtr := err[0]
            if errPtr != nil {
                // error occurred, set success to false and Error to the error message
                zp.Success = false
                zp.Error = errPtr.Error()
            } else {
                zp.Success = true
            }
        }
    }
    

    If you can't change the signature, you just need to dereference the pointer:

    zp.Error = (*errPtr).Error()
    

    Playground example here: https://play.golang.org/p/dxT108660l

    Errors are also covered in the Go tour.

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

报告相同问题?

悬赏问题

  • ¥15 fluent里模拟降膜反应的UDF编写
  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
  • ¥15 神经网络模型一直不能上GPU
  • ¥15 pyqt怎么把滑块和输入框相互绑定,求解决!
  • ¥20 wpf datagrid单元闪烁效果失灵
  • ¥15 券商软件上市公司信息获取问题
  • ¥100 ensp启动设备蓝屏,代码clock_watchdog_timeout