github.com/akamai/AkamaiOPEN-edgegrid-golang/v2@v2.17.0/pkg/imaging/errors.go (about) 1 package imaging 2 3 import ( 4 "encoding/json" 5 "errors" 6 "fmt" 7 "io/ioutil" 8 "net/http" 9 ) 10 11 type ( 12 // Error is an Image and Video Manager error implementation 13 Error struct { 14 Type string `json:"type,omitempty"` 15 Title string `json:"title,omitempty"` 16 Detail string `json:"detail,omitempty"` 17 Instance string `json:"instance,omitempty"` 18 Status int `json:"status,omitempty"` 19 ProblemID string `json:"problemId,omitempty"` 20 RequestID string `json:"requestId,omitempty"` 21 IllegalValue string `json:"illegalValue,omitempty"` 22 ParameterName string `json:"parameterName,omitempty"` 23 ExtensionFields map[string]string `json:"extensionFields,omitempty"` 24 Method string `json:"method,omitempty"` 25 ServerIP string `json:"serverIp,omitempty"` 26 ClientIP string `json:"clientIp,omitempty"` 27 RequestTime string `json:"requestTime,omitempty"` 28 AuthzRealm string `json:"authzRealm,omitempty"` 29 } 30 ) 31 32 // Error parses an error from the response 33 func (i *imaging) Error(r *http.Response) error { 34 var e Error 35 var body []byte 36 body, err := ioutil.ReadAll(r.Body) 37 if err != nil { 38 i.Log(r.Request.Context()).Errorf("reading error response body: %s", err) 39 e.Status = r.StatusCode 40 e.Title = "Failed to read error body" 41 e.Detail = err.Error() 42 return &e 43 } 44 45 if err := json.Unmarshal(body, &e); err != nil { 46 i.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err) 47 e.Title = string(body) 48 e.Status = r.StatusCode 49 } 50 return &e 51 } 52 53 func (e *Error) Error() string { 54 msg, err := json.MarshalIndent(e, "", "\t") 55 if err != nil { 56 return fmt.Sprintf("error marshaling API error: %s", err) 57 } 58 return fmt.Sprintf("API error: \n%s", msg) 59 } 60 61 // Is handles error comparisons 62 func (e *Error) Is(target error) bool { 63 var t *Error 64 if !errors.As(target, &t) { 65 return false 66 } 67 68 if e == t { 69 return true 70 } 71 72 if e.Status != t.Status { 73 return false 74 } 75 76 return e.Error() == t.Error() 77 }