-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement a specific error type for API responses
Signed-off-by: Miquel Sabaté Solà <[email protected]>
- Loading branch information
Showing
3 changed files
with
40 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
package connection | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"net/http" | ||
) | ||
|
||
// ApiError contains all the information for any given API error response. Don't | ||
// build it directly, but use `ErrorFromResponse` instead. | ||
type ApiError struct { | ||
Code int | ||
Message string `json:"error"` | ||
LocalizedMessage string `json:"localized_error"` | ||
} | ||
|
||
func (ae *ApiError) Error() string { | ||
if ae.LocalizedMessage != "" { | ||
return fmt.Sprintf("API error: %v (code: %v)", ae.LocalizedMessage, ae.Code) | ||
} | ||
return fmt.Sprintf("API error: %v (code: %v)", ae.Message, ae.Code) | ||
} | ||
|
||
// Returns a new ApiError from the given response if it contained an API error | ||
// response. Otherwise it just returns nil. | ||
func ErrorFromResponse(resp *http.Response) *ApiError { | ||
if resp.StatusCode >= 200 && resp.StatusCode < 300 { | ||
return nil | ||
} | ||
|
||
ae := &ApiError{Code: resp.StatusCode} | ||
if err := json.NewDecoder(resp.Body).Decode(ae); err != nil { | ||
return nil | ||
} | ||
return ae | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters