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

     1  package datastream
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net/http"
     9  )
    10  
    11  type (
    12  	// Error is a ds 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"`
    18  		StatusCode int             `json:"statusCode"`
    19  		Errors     []RequestErrors `json:"errors"`
    20  	}
    21  
    22  	// RequestErrors is an optional errors array that lists potentially more than one problem detected in the request
    23  	RequestErrors struct {
    24  		Type     string `json:"type"`
    25  		Title    string `json:"title"`
    26  		Instance string `json:"instance,omitempty"`
    27  		Detail   string `json:"detail"`
    28  	}
    29  )
    30  
    31  // Error parses an error from the response
    32  func (d *ds) Error(r *http.Response) error {
    33  	var e Error
    34  
    35  	var body []byte
    36  
    37  	body, err := ioutil.ReadAll(r.Body)
    38  	if err != nil {
    39  		d.Log(r.Request.Context()).Errorf("reading error response body: %s", err)
    40  		e.StatusCode = r.StatusCode
    41  		e.Title = fmt.Sprintf("Failed to read error body")
    42  		e.Detail = err.Error()
    43  		return &e
    44  	}
    45  
    46  	if err := json.Unmarshal(body, &e); err != nil {
    47  		d.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err)
    48  		e.Title = fmt.Sprintf("Failed to unmarshal error body")
    49  		e.Detail = err.Error()
    50  	}
    51  
    52  	e.StatusCode = r.StatusCode
    53  
    54  	return &e
    55  }
    56  
    57  func (e *Error) Error() string {
    58  	msg, err := json.MarshalIndent(e, "", "\t")
    59  	if err != nil {
    60  		return fmt.Sprintf("error marshaling API error: %s", err)
    61  	}
    62  	return fmt.Sprintf("API error: \n%s", msg)
    63  }
    64  
    65  // Is handles error comparisons
    66  func (e *Error) Is(target error) bool {
    67  	var t *Error
    68  	if !errors.As(target, &t) {
    69  		return false
    70  	}
    71  
    72  	if e == t {
    73  		return true
    74  	}
    75  
    76  	if e.StatusCode != t.StatusCode {
    77  		return false
    78  	}
    79  
    80  	return e.Error() == t.Error()
    81  }