github.com/akamai/AkamaiOPEN-edgegrid-golang/v8@v8.1.0/pkg/clientlists/errors.go (about)

     1  package clientlists
     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 Client Lists 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,omitempty"`
    20  		BehaviorName  string `json:"behaviorName,omitempty"`
    21  		ErrorLocation string `json:"errorLocation,omitempty"`
    22  		StatusCode    int    `json:"-"`
    23  	}
    24  )
    25  
    26  // Error parses an error from the response
    27  func (p *clientlists) 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  		p.Log(r.Request.Context()).Errorf("reading error response body: %s", err)
    35  		e.StatusCode = r.StatusCode
    36  		e.Title = "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  		p.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err)
    43  		e.Title = "Failed to unmarshal error body. Client Lists API failed. Check details for more information."
    44  		e.Detail = errs.UnescapeContent(string(body))
    45  	}
    46  
    47  	e.StatusCode = r.StatusCode
    48  
    49  	return &e
    50  }
    51  
    52  func (e *Error) Error() string {
    53  	return fmt.Sprintf("Title: %s; Type: %s; Detail: %s", e.Title, e.Type, e.Detail)
    54  }
    55  
    56  // Is handles error comparisons
    57  func (e *Error) Is(target error) bool {
    58  	var t *Error
    59  	if !errors.As(target, &t) {
    60  		return false
    61  	}
    62  
    63  	if e == t {
    64  		return true
    65  	}
    66  
    67  	if e.StatusCode != t.StatusCode {
    68  		return false
    69  	}
    70  
    71  	return e.Error() == t.Error()
    72  }