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