关闭
dsmvovm27249 2017-05-02 20:30
浏览 76
已采纳

在Golang中自定义错误结构

The default structure for error messages in golang contains a string but I want to add dynamic response code and the time the error occurred to it. Any suggestions on how to do it?

  • 写回答

1条回答 默认 最新

  • dongzaijiao4863 2017-05-02 20:57
    关注

    error in not a struct, is an interface.

    type error interface {
        Error() string
    }
    

    you can define your own error struct, just implement the Error() string function.

    type ErrorA struct {
        // any field you want
    }
    
    func (e ErrorA) Error() string {
        // implement this function
    }
    

    then ErrorA can be used as error.

    ref:
    1. https://golang.org/ref/spec#Errors
    2. https://golang.org/ref/spec#Interface_types

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部