-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_error.go
54 lines (47 loc) · 1.16 KB
/
api_error.go
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
package keycloak
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
type APIError struct {
SuccessCode int `json:"success_code"`
ResponseCode int `json:"response_code"`
ResponseStatus string `json:"response_status"`
ResponseHeaders http.Header `json:"response_headers"`
Err string `json:"error"`
ErrDescription string `json:"error_description"`
}
func newAPIError(successCode int, resp *http.Response) *APIError {
e := new(APIError)
e.SuccessCode = successCode
e.ResponseCode = resp.StatusCode
e.ResponseStatus = resp.Status
e.ResponseHeaders = resp.Header
b, _ := ioutil.ReadAll(resp.Body)
if len(b) > 0 {
if err := json.Unmarshal(b, e); err != nil {
e.ErrDescription = string(b)
}
}
return e
}
func (e *APIError) Error() string {
if e.ResponseCode == 0 {
return ""
}
return fmt.Sprintf("Call returned non-%d: status=%q; error=%q; error_description=%q", e.SuccessCode, e.ResponseStatus, e.Err, e.ErrDescription)
}
func IsAPIError(err error) bool {
if err == nil {
return false
}
_, ok := err.(*APIError)
for err != nil && !ok {
err = errors.Unwrap(err)
_, ok = err.(*APIError)
}
return ok
}