Go: JSON Marshaling an error
go, marshalling
Solution
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.
Problem
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?