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