github.com/seeker-insurance/kit@v0.0.13/jsonapi/errors.go (about)

     1  package jsonapi
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  )
     8  
     9  // MarshalErrors writes a JSON API response using the given `[]error`.
    10  //
    11  // For more information on JSON API error payloads, see the spec here:
    12  // http://jsonapi.org/format/#document-top-level
    13  // and here: http://jsonapi.org/format/#error-objects.
    14  func MarshalErrors(w io.Writer, errorObjects []*ErrorObject) error {
    15  	if err := json.NewEncoder(w).Encode(&ErrorsPayload{Errors: errorObjects}); err != nil {
    16  		return err
    17  	}
    18  	return nil
    19  }
    20  
    21  // ErrorsPayload is a serializer struct for representing a valid JSON API errors payload.
    22  type ErrorsPayload struct {
    23  	Errors []*ErrorObject `json:"errors"`
    24  }
    25  
    26  // ErrorObject is an `Error` implementation as well as an implementation of the JSON API error object.
    27  //
    28  // The main idea behind this struct is that you can use it directly in your code as an error type
    29  // and pass it directly to `MarshalErrors` to get a valid JSON API errors payload.
    30  // For more information on Golang errors, see: https://golang.org/pkg/errors/
    31  // For more information on the JSON API spec's error objects, see: http://jsonapi.org/format/#error-objects
    32  type ErrorObject struct {
    33  	// ID is a unique identifier for this particular occurrence of a problem.
    34  	ID string `json:"id,omitempty"`
    35  
    36  	// Title is a short, human-readable summary of the problem that SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localization.
    37  	Title string `json:"title,omitempty"`
    38  
    39  	// Detail is a human-readable explanation specific to this occurrence of the problem. Like title, this field’s value can be localized.
    40  	Detail string `json:"detail,omitempty"`
    41  
    42  	// Status is the HTTP status code applicable to this problem, expressed as a string value.
    43  	Status string `json:"status,omitempty"`
    44  
    45  	// Code is an application-specific error code, expressed as a string value.
    46  	Code string `json:"code,omitempty"`
    47  
    48  	// Meta is an object containing non-standard meta-information about the error.
    49  	Meta *map[string]interface{} `json:"meta,omitempty"`
    50  }
    51  
    52  // Error implements the `Error` interface.
    53  func (e *ErrorObject) Error() string {
    54  	return fmt.Sprintf("Error: %s %s\n", e.Title, e.Detail)
    55  }