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