Skip to content

Commit

Permalink
Add typed error response to error object returned by helper
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiante committed Jan 19, 2024
1 parent 6b1d5e2 commit 438a729
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions err.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package easclient

import (
"encoding/json"
"fmt"

"gopkg.in/resty.v1"
Expand All @@ -10,10 +11,30 @@ const (
HeaderKeyOtrisErr = "X-Otris-Eas-Error"
)

// errorResponse is the response body of an eas response where
// the HeaderKeyOtrisErr is set. It contains details about why something failed.
type errorResponse struct {
Message string `json:"message"`
Code int `json:"code"`
}

type ResponseErr struct {
msg string

Body []byte

// Response is the original error response from the EAS. This may contain
// zero values if the EAS did not return a valid error response.
Response errorResponse
}

func NewResponseErr(msg string, body []byte) *ResponseErr {
err := &ResponseErr{msg: msg, Body: body}

// try to parse EAS response. If it fails, we ignore it.
_ = json.Unmarshal(body, &err.Response)

return err
}

func (r *ResponseErr) Error() string {
Expand All @@ -23,16 +44,10 @@ func (r *ResponseErr) Error() string {
// isErrorResponse checks if the given response is an error.
func isErrorResponse(res *resty.Response) (bool, *ResponseErr) {
if status := res.StatusCode(); status > 300 {
return true, &ResponseErr{
msg: fmt.Sprintf("unexpected response status %v, expected value < 300", status),
Body: res.Body(),
}
return true, NewResponseErr(fmt.Sprintf("unexpected response status %v, expected value < 300", status), res.Body())
}
if hasErrHeader(res) {
return true, &ResponseErr{
msg: fmt.Sprintf("eas responded with error header. status %v is considered an error in that case", res.StatusCode()),
Body: res.Body(),
}
return true, NewResponseErr(fmt.Sprintf("eas responded with error header. status %v is considered an error in that case", res.StatusCode()), res.Body())
}

return false, nil
Expand Down

0 comments on commit 438a729

Please sign in to comment.