diff --git a/types.go b/types.go index 50a5cd0..dc4f080 100644 --- a/types.go +++ b/types.go @@ -571,6 +571,32 @@ func (er ErrorResponse) Error() string { return er.Detail } +func (er ErrorResponse) Format(f fmt.State, c rune) { + switch c { + case 'v': + if f.Flag('+') { + meta := make([]string, 0, len(er.Meta.Errors)) + for _, e := range er.Meta.Errors { + meta = append(meta, + fmt.Sprintf( + "(type [%s]; loc [%s]; input [%s]; msg [%s])", + e.Type, strings.Join(e.Loc, "."), e.Input, e.Message)) + } + + fmt.Fprintf(f, "error: %s (ID: %s; Status: %d; Code: %s); details: %s", + er.Detail, er.ID, er.Status, er.Code, strings.Join(meta, ", ")) + } else { + fmt.Fprint(f, er.Detail) + } + case 's': + fmt.Fprint(f, er.Detail) + case 'q': + fmt.Fprintf(f, "%q", er.Detail) + default: + fmt.Fprint(f, er.Detail) + } +} + type ErrorMeta struct { Component string `json:"component"` Errors []ErrorMetaError `json:"errors"` @@ -581,6 +607,7 @@ type ErrorMetaError struct { Message string `json:"msg"` Type string `json:"type"` Context ErrorContext `json:"ctx"` + Input string `json:"input"` } type ErrorContext struct { diff --git a/types_test.go b/types_test.go index 1323e34..3057462 100644 --- a/types_test.go +++ b/types_test.go @@ -2,9 +2,11 @@ package brave_test import ( "encoding/json" + "fmt" "testing" "dev.freespoke.com/brave-search" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -21,3 +23,18 @@ func TestTimestampUnmarshal(t *testing.T) { require.False(t, ts.Time().IsZero(), c) } } + +func TestErrorResponse(t *testing.T) { + var resp brave.ErrorResponse + if err := json.Unmarshal(errJSON, &resp); err != nil { + t.Fatal(err) + } + + p := fmt.Sprintf("%+v", resp) + assert.Equal(t, + "error: Unable to validate request parameter(s) (ID: f49c8ffa-5ddc-4fbf-9841-6b3093c21eb2; Status: 422; Code: VALIDATION); details: (type [int_parsing]; loc [query.offset]; input [foo]; msg [Input should be a valid integer, unable to parse string as an integer])", + p, + ) +} + +var errJSON = []byte(`{"id": "f49c8ffa-5ddc-4fbf-9841-6b3093c21eb2","status": 422,"code": "VALIDATION","detail": "Unable to validate request parameter(s)","meta": {"errors": [{"type": "int_parsing","loc": ["query","offset"],"msg": "Input should be a valid integer, unable to parse string as an integer","input": "foo"}]}}`)