去:JSON封送一个错误 [英] Go: JSON Marshaling an error

查看:137
本文介绍了去:JSON封送一个错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例回应:

我在Go中构建JSON API并且想要将错误响应作为json返回。

  {
error:无效的请求语法
}

我认为我可以创建一个实现错误接口的包装器结构,然后使用Go的json封送器作为一种干净的方式来获取错误的json表示形式:

 类型JsonErr结构{
Err错误`json:error`
}
func ()






这只会将JsonErr编组为 {error:{}} ,是否有使用默认Go json封送拆收器编码此结构的方法,或者我是否需要为JsonErr结构编写一个快速定制的MarshalJson? rel =nofollow> json.Marshaler 界面:

  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
}

它不起作用的原因是因为 json.Marshal 没有检测到错误接口,大多数错误类型没有导出的字段。反射无法显示这些字段。


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?

解决方案

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.

这篇关于去:JSON封送一个错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆