github.com/akamai/AkamaiOPEN-edgegrid-golang/v8@v8.1.0/pkg/cps/errors.go (about) 1 package cps 2 3 import ( 4 "encoding/json" 5 "errors" 6 "fmt" 7 "io/ioutil" 8 "net/http" 9 ) 10 11 type ( 12 // Error is a cps error interface 13 Error struct { 14 Type string `json:"type"` 15 Title string `json:"title"` 16 Detail string `json:"detail"` 17 Instance string `json:"instance,omitempty"` 18 BehaviorName string `json:"behaviorName,omitempty"` 19 ErrorLocation string `json:"errorLocation,omitempty"` 20 StatusCode int `json:"statusCode,omitempty"` 21 Errors json.RawMessage `json:"errors,omitempty"` 22 Warnings json.RawMessage `json:"warnings,omitempty"` 23 } 24 ) 25 26 // Error parses an error from the response 27 func (c *cps) Error(r *http.Response) error { 28 var e Error 29 30 var body []byte 31 32 body, err := ioutil.ReadAll(r.Body) 33 if err != nil { 34 c.Log(r.Request.Context()).Errorf("reading error response body: %s", err) 35 e.StatusCode = r.StatusCode 36 e.Title = fmt.Sprintf("Failed to read error body") 37 e.Detail = err.Error() 38 return &e 39 } 40 41 if err := json.Unmarshal(body, &e); err != nil { 42 c.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err) 43 e.Title = "Failed to unmarshal error body. CPS API failed. Check details for more information." 44 e.Detail = string(body) 45 } 46 47 e.StatusCode = r.StatusCode 48 49 return &e 50 } 51 52 func (e *Error) Error() string { 53 msg, err := json.MarshalIndent(e, "", "\t") 54 if err != nil { 55 return fmt.Sprintf("error marshaling API error: %s", err) 56 } 57 return fmt.Sprintf("API error: \n%s", msg) 58 } 59 60 // Is handles error comparisons 61 func (e *Error) Is(target error) bool { 62 var t *Error 63 if !errors.As(target, &t) { 64 return false 65 } 66 67 if e == t { 68 return true 69 } 70 71 if e.StatusCode != t.StatusCode { 72 return false 73 } 74 75 return e.Error() == t.Error() 76 }