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