Skip to content

Proposal: Ability to JSON errors with private fields #14

@PROger4ever

Description

@PROger4ever

Hello.
It would be very useful to have a builtin way to Marshal and Unmarshal validation errors completely (including fields "code" and "message"). This feature will allow us to send validation errors directly to API clients without wrapping them, etc.
I see the following 2 ways to implement it:

  1. Make "code" and "message" public. This makes uncontrollable changes to be possible.
  2. Add custom marshaling/unmarshaling to error structs like this:
func (e *Validation) MarshalJSON() ([]byte, error) {
	return json.Marshal(map[string]interface{}{
		"code": e.code,
		"name": e.Name,
		"in": e.In,
		"value": e.Value,
		"message": e.message,
		"values": e.Values,
	})
}

func (e *Validation) UnmarshalJSON(data []byte) error {
	theMap := make(map[string]interface{})
	err := json.Unmarshal(data, theMap)
	if err != nil {
		return err
	}

	e.code = theMap["code"].(int32)
	e.Name = theMap["name"].(string)
	e.In = theMap["in"].(string)
	e.Value = theMap["value"]
	e.message = theMap["message"].(string)
	e.Values = theMap["values"].([]interface{})
	return nil
}

Could you implement this feature, please?
Thank you in advance.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions