Skip to content

JSON formatting for an error #21

@uded

Description

@uded

It would be, IMHO, reasonable to make a custom MarshalJSON() function to handle marshaling given Error with all printable properties and, potentially, stack trace to JSON. Maybe not all will need this, but a lot of folks are using some Web framework, and that might come in handy...

As I am happy to make the implementation, I have two open questions which need an answer to address a variety of needs, not the one I see at this point:

  1. As I assume the format can be something like:
    { 
        "msg": "error was here",
        "properties": {
            "propertyString": "value",
            "propertyInt": 123
        }
    }
    I am not sure if the stacked errors should appear as a loop under some property like cause and so on? Just thinking here. One more single cause property with a message might be also sufficient, but I am not certain which would be more useful here...
  2. As I am new to this package, am I missing something that should be handled by MarshalJSON on top of that? Just asking as I am really not sure if there is something I am missing otherwise...

A really quick and simple implementation can be as follows:

func (e *Error) MarshalJSON() ([]byte, error) {
	return json.Marshal(&struct {
		Message    string                 `json:"message"`
		Properties map[string]interface{} `json:"properties,omitempty"`
	}{
		Message: e.message,
		Properties: e.mapFromPrintableProperties(),
	})
}

func (e *Error) mapFromPrintableProperties() map[string]interface{} {
	uniq := make(map[string]interface{}, e.printablePropertyCount)
	for m := e.properties; m != nil; m = m.next {
		if !m.p.printable {
			continue
		}
		if _, ok := uniq[m.p.label]; ok {
			continue
		}
		uniq[m.p.label] = m.value
	}
	return uniq
}

Happy to make a PR if that is acceptable for a larger audience

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions