-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathapi_error.go
More file actions
56 lines (50 loc) · 1.35 KB
/
api_error.go
File metadata and controls
56 lines (50 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package blnkgo
import (
"fmt"
"io"
"net/http"
)
//This function will take in Resp as a parameter and check the status code, for error in the range of 400 return a 400 error, for error in the range of 500 return a 500 error, for success return nil
// we create a struct for api error response
type ApiErrorResponse struct {
Status int `json:"status"`
Message string `json:"message"`
Body []byte `json:"body"`
}
// implement the error interface for ApiErrorResponse
func (a *ApiErrorResponse) Error() string {
return fmt.Sprintf("Status: %d, Message: %s, Body: %s", a.Status, a.Message, a.Body)
}
func (c *Client) CheckResponse(resp *http.Response) error {
if resp.StatusCode >= 400 && resp.StatusCode < 500 {
//read the response body
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
//create a new api error response
apiErrorResponse := &ApiErrorResponse{
Status: resp.StatusCode,
Message: resp.Status,
Body: body,
}
//return the error
return apiErrorResponse
}
if resp.StatusCode >= 500 {
//read the response body
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
//create a new api error response
apiErrorResponse := &ApiErrorResponse{
Status: resp.StatusCode,
Message: resp.Status,
Body: body,
}
//return the error
return apiErrorResponse
}
return nil
}