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