Go: JSON Marshaling an error

为君一笑 提交于 2019-12-24 03:00:13

问题


I'm building a JSON API in Go and I'd like to return error responses as json.

Example response:

{
    "error": "Invalid request syntax"
}

I thought that I could create a wrapper struct that implements the error interface, and then use Go's json marshaler as a clean way to get the json representation of the error:

type JsonErr struct {
    Err error `json:"error"`
}
func (t JsonErr) Error() string {
    return t.Err.Error()
}

This will just marshal a JsonErr as {"error":{}}, is there a way of using the default Go json marshaler to encode this struct, or do I need to write a quick custom MarshalJson for JsonErr structs?


回答1:


Just implement the json.Marshaler interface:

func main() {
    var err error = JsonErr{errors.New("expected")}
    json.NewEncoder(os.Stdout).Encode(err)
}

type JsonErr struct {
    error
}

func (t JsonErr) MarshalJSON() ([]byte, error) {
    return []byte(`{"error": "` + t.Error() + `"}`), nil
}

The reason it doesn't work is because json.Marshal has no detection for the error interface and most error types have no exported fields so reflection can't display those fields.



来源:https://stackoverflow.com/questions/28596376/go-json-marshaling-an-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!