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

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