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

     1  package hapi
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net/http"
     9  )
    10  
    11  type (
    12  	// Error is a hapi 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  		RequestInstance string      `json:"requestInstance,omitempty"`
    19  		Method          string      `json:"method,omitempty"`
    20  		RequestTime     string      `json:"requestTime,omitempty"`
    21  		BehaviorName    string      `json:"behaviorName,omitempty"`
    22  		ErrorLocation   string      `json:"errorLocation,omitempty"`
    23  		Status          int         `json:"status,omitempty"`
    24  		DomainPrefix    string      `json:"domainPrefix,omitempty"`
    25  		DomainSuffix    string      `json:"domainSuffix,omitempty"`
    26  		Errors          []ErrorItem `json:"errors,omitempty"`
    27  	}
    28  
    29  	// ErrorItem represents single error item
    30  	ErrorItem struct {
    31  		Key   string `json:"key,omitempty"`
    32  		Value string `json:"value,omitempty"`
    33  	}
    34  )
    35  
    36  // Error parses an error from the response
    37  func (h *hapi) Error(r *http.Response) error {
    38  	var e Error
    39  
    40  	var body []byte
    41  
    42  	body, err := ioutil.ReadAll(r.Body)
    43  	if err != nil {
    44  		h.Log(r.Request.Context()).Errorf("reading error response body: %s", err)
    45  		e.Status = r.StatusCode
    46  		e.Title = fmt.Sprintf("Failed to read error body")
    47  		e.Detail = err.Error()
    48  		return &e
    49  	}
    50  
    51  	if err := json.Unmarshal(body, &e); err != nil {
    52  		h.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err)
    53  		e.Title = fmt.Sprintf("Failed to unmarshal error body")
    54  		e.Detail = err.Error()
    55  	}
    56  
    57  	e.Status = r.StatusCode
    58  
    59  	return &e
    60  }
    61  
    62  func (e *Error) Error() string {
    63  	msg, err := json.MarshalIndent(e, "", "\t")
    64  	if err != nil {
    65  		return fmt.Sprintf("error marshaling API error: %s", err)
    66  	}
    67  	return fmt.Sprintf("API error: \n%s", msg)
    68  }
    69  
    70  // Is handles error comparisons
    71  func (e *Error) Is(target error) bool {
    72  	var t *Error
    73  	if !errors.As(target, &t) {
    74  		return false
    75  	}
    76  
    77  	if e == t {
    78  		return true
    79  	}
    80  
    81  	if e.Status != t.Status {
    82  		return false
    83  	}
    84  
    85  	return e.Error() == t.Error()
    86  }