Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(geocodingsearchv7): export ResponseError and add status code to it #157

Merged
merged 1 commit into from
Oct 16, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 28 additions & 10 deletions geocodingsearchv7/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,17 @@ type service struct {
Client *Client
}

// A responseError reports the error caused by an API request.
type responseError struct {
// A ResponseError reports the error caused by an API request.
type ResponseError struct {
// HTTP response that caused this error
Response *HereErrorResponse
// The HTTP body of the error response
HTTPBody string
// The HTTP status code of the response
HTTPStatusCode int
}

func (r *responseError) Error() string {
func (r *ResponseError) Error() string {
return fmt.Sprintf(
"Title: %v, Status: %d, Code: %v, Cause: %v, Action: %v",
r.Response.Title,
Expand Down Expand Up @@ -153,12 +157,21 @@ func checkResponse(r *http.Response) error {
if c := r.StatusCode; c >= 200 && c <= 299 {
return nil
}
buf := new(bytes.Buffer)
_, err := io.Copy(buf, r.Body)
if err != nil {
return err
}
var response HereErrorResponse
err := json.NewDecoder(r.Body).Decode(&response)
err = json.Unmarshal(buf.Bytes(), &response)
if err != nil {
return err
}
return &responseError{Response: &response}
return &ResponseError{
Response: &response,
HTTPBody: buf.String(),
HTTPStatusCode: r.StatusCode,
}
}

// DoXML sends an API request and returns the API response. The API response is XML decoded and stored in the value
Expand Down Expand Up @@ -204,14 +217,19 @@ func checkResponseXML(r *http.Response) error {
if c := r.StatusCode; c >= 200 && c <= 299 {
return nil
}
response := &HereErrorResponse{}
data, err := io.ReadAll(r.Body)
buf := new(bytes.Buffer)
_, err := io.Copy(buf, r.Body)
if err != nil {
return fmt.Errorf("failed to read error body: %w", err)
return err
}
err = xml.Unmarshal(data, response)
response := HereErrorResponse{}
err = xml.Unmarshal(buf.Bytes(), &response)
if err != nil {
return fmt.Errorf("failed unmarshal error: %w", err)
}
return &responseError{Response: response}
return &ResponseError{
Response: &response,
HTTPBody: buf.String(),
HTTPStatusCode: r.StatusCode,
}
}