Golang error types are empty when encoded in JSON

I am trying to encode some JSON for a REST api, everything works fine except for some errors. For example, using this structure:

type TemplateResponse struct {
    Message string
    Error   error
    Template Template
}

Encoded by this data:

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)

Return:

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

I get this, it would seem, randomly in my application, where the types of "errors" are returned as empty. Any ideas?

Thank!

+4
source share
1 answer

Because error- this is just an interface. It can contain the value of any particular type that implements it.

fmt.Errorf() error. errors.New(), errors.errorString. :

type errorString struct {
    s string
}

, ( ), JSON: {}.

"": "" , , JSON . , ( error.Error()), Error error , :

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

, / ErrorMsg .

, error , :

type TemplateResponse struct {
    Message  string
    ErrorMsg string
    Template Template
}

Error error ( ErrorMsg), , json.Marshaler, "" error string ( , ).

+7

Source: https://habr.com/ru/post/1681034/


All Articles