github.com/akamai/AkamaiOPEN-edgegrid-golang/v2@v2.17.0/pkg/cps/errors.go (about)

     1  package cps
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net/http"
     9  )
    10  
    11  type (
    12  	// Error is a cps error interface
    13  	Error struct {
    14  		Type          string          `json:"type"`
    15  		Title         string          `json:"title"`
    16  		Detail        string          `json:"detail"`
    17  		Instance      string          `json:"instance,omitempty"`
    18  		BehaviorName  string          `json:"behaviorName,omitempty"`
    19  		ErrorLocation string          `json:"errorLocation,omitempty"`
    20  		StatusCode    int             `json:"statusCode,omitempty"`
    21  		Errors        json.RawMessage `json:"errors,omitempty"`
    22  		Warnings      json.RawMessage `json:"warnings,omitempty"`
    23  	}
    24  )
    25  
    26  // Error parses an error from the response
    27  func (c *cps) Error(r *http.Response) error {
    28  	var e Error
    29  
    30  	var body []byte
    31  
    32  	body, err := ioutil.ReadAll(r.Body)
    33  	if err != nil {
    34  		c.Log(r.Request.Context()).Errorf("reading error response body: %s", err)
    35  		e.StatusCode = r.StatusCode
    36  		e.Title = fmt.Sprintf("Failed to read error body")
    37  		e.Detail = err.Error()
    38  		return &e
    39  	}
    40  
    41  	if err := json.Unmarshal(body, &e); err != nil {
    42  		c.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err)
    43  		e.Title = string(body)
    44  	}
    45  
    46  	e.StatusCode = r.StatusCode
    47  
    48  	return &e
    49  }
    50  
    51  func (e *Error) Error() string {
    52  	msg, err := json.MarshalIndent(e, "", "\t")
    53  	if err != nil {
    54  		return fmt.Sprintf("error marshaling API error: %s", err)
    55  	}
    56  	return fmt.Sprintf("API error: \n%s", msg)
    57  }
    58  
    59  // Is handles error comparisons
    60  func (e *Error) Is(target error) bool {
    61  	var t *Error
    62  	if !errors.As(target, &t) {
    63  		return false
    64  	}
    65  
    66  	if e == t {
    67  		return true
    68  	}
    69  
    70  	if e.StatusCode != t.StatusCode {
    71  		return false
    72  	}
    73  
    74  	return e.Error() == t.Error()
    75  }