编码为 JSON 时,Golang 错误类型为空 [英] Golang Error Types are empty when encoded to JSON

查看:49
本文介绍了编码为 JSON 时,Golang 错误类型为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 REST api 编码一些 JSON,除了一些错误外,一切正常.例如,使用这个结构:

I'm trying to encode some JSON for a REST api, everything is working fine except for some errors. For example, with this struct:

type TemplateResponse struct {
    Message string
    Error   error
    Template Template
}

使用此数据编码:

res := TemplateResponse{"Template not found.", fmt.Errorf("There is no template on this host with the name " + vars["name"]), Template{}}
json.NewEncoder(w).Encode(res)

返回:

{
  "Message": "Template not found.",
  "Error": {},
  "Template": {
    "Name": "",
    "Disabled": false,
    "Path": "",
    "Version": ""
  }
}

我在我的应用程序中似乎随机地得到了这个,其中错误"类型被返回为空.有什么想法吗?

I'm getting this seemingly randomly across my application, where 'error' types are being returned as empty. Any ideas?

谢谢!

推荐答案

因为 error 只是一个接口.它可以包含实现它的任何具体类型的值.

Because error is just an interface. It may hold a value of any concrete type that implements it.

在您的示例中,您使用了 fmt.Errorf()创建一个 error 值.调用 errors.New() 返回一个指向未导出的 errors.errorString 结构的值.它的定义是:

In your example you used fmt.Errorf() to create an error value. That calls errors.New() which returns a pointer to a value of the unexported errors.errorString struct. Its definition is:

type errorString struct {
    s string
}

此结构值将被封送处理,但由于它没有导出字段(仅对导出字段进行封送处理),它将是一个空的 JSON 对象:{}.

This struct value will be marshaled, but since it has no exported fields (only exported fields are marshaled), it will be an empty JSON object: {}.

修复"是:不要编组通用"接口的值,依靠动态值可以有意义地编组为 JSON.相反,您应该添加一个存储错误字符串的字段(error.Error() 的结果),并在编组中省略 Error error 字段,例如:

The "fix" is: don't marshal values of "general" interfaces, relying on that the dynamic values can be marshaled into JSON meaningfully. Instead you should add a field that stores the error string (the result of error.Error()), and omit the Error error field from marshaling, e.g.:

type TemplateResponse struct {
    Message  string
    Error    error `json:"-"`
    ErrorMsg string
    Template Template
}

当然,您还需要在编组之前设置/填充 ErrorMsg 字段.

Of course then you also need to set / fill the ErrorMsg field before marshaling.

或者如果您不需要在结构中存储 error 值,请完全删除该字段:

Or if you don't need to store the error value in the struct, remove that field completely:

type TemplateResponse struct {
    Message  string
    ErrorMsg string
    Template Template
}

如果您仍想保留 Error error 字段(而不是 ErrorMsg 字段),那么您需要通过实现 json.Marshaler 接口,您可以在其中转换"例如,将 error 值转换为有意义的 string(或转换为另一个可以正确编组的值).

If you still want to keep the Error error field (and not the ErrorMsg field), then you need to implement a custom marshaling logic by implementing the json.Marshaler interface where you can "convert" the error value to a meaningful string for example (or into another value that can be marshaled properly).

这篇关于编码为 JSON 时,Golang 错误类型为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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