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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。