Skip to content

Commit

Permalink
implement fmt.Formatter in ErrorResponse (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
jdpedrie authored Jun 7, 2024
1 parent 345818b commit 41c0fd8
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
27 changes: 27 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand All @@ -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 {
Expand Down
17 changes: 17 additions & 0 deletions types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand All @@ -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"}]}}`)

0 comments on commit 41c0fd8

Please sign in to comment.