Skip to content

Commit

Permalink
clienterrors: add (one possible) way to fix the missing errors
Browse files Browse the repository at this point in the history
  • Loading branch information
mvo5 committed May 8, 2024
1 parent 7316e67 commit bba6087
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
27 changes: 24 additions & 3 deletions internal/worker/clienterrors/errors.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package clienterrors

import (
"encoding/json"
"fmt"
)

Expand Down Expand Up @@ -49,15 +50,35 @@ const (
type ClientErrorCode int

type Error struct {
ID ClientErrorCode `json:"id"`
Reason string `json:"reason"`
Details interface{} `json:"details,omitempty"`
ID ClientErrorCode
Reason string
Details interface{}
}

func (e *Error) String() string {
return fmt.Sprintf("Code: %d, Reason: %s, Details: %v", e.ID, e.Reason, e.Details)
}

func (e *Error) MarshalJSON() ([]byte, error) {
var details interface{}
switch v := e.Details.(type) {
case error:
details = v.Error()
default:
details = v
}

return json.Marshal(&struct {
ID ClientErrorCode `json:"id"`
Reason string `json:"reason"`
Details interface{} `json:"details,omitempty"`
}{
ID: e.ID,
Reason: e.Reason,
Details: details,
})
}

const (
JobStatusSuccess = "2xx"
JobStatusUserInputError = "4xx"
Expand Down
2 changes: 1 addition & 1 deletion internal/worker/clienterrors/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,5 @@ func TestErrorJSONMarshal(t *testing.T) {

json, err := json.Marshal(clienterrors.WorkerClientError(2, "details", err))
assert.NoError(t, err)
assert.Equal(t, `{"id":2,"reason":"details","details":{"some-error"}}`, string(json))
assert.Equal(t, `{"id":2,"reason":"details","details":"some-error"}`, string(json))
}

0 comments on commit bba6087

Please sign in to comment.