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

     1  package iam
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net/http"
     9  )
    10  
    11  type (
    12  	// Error is an IAM 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  		BehaviorName  string          `json:"behaviorName,omitempty"`
    19  		ErrorLocation string          `json:"errorLocation,omitempty"`
    20  		StatusCode    int             `json:"statusCode,omitempty"`
    21  		Errors        json.RawMessage `json:"errors,omitempty"`
    22  		Warnings      json.RawMessage `json:"warnings,omitempty"`
    23  		HTTPStatus    int             `json:"httpStatus,omitempty"`
    24  	}
    25  )
    26  
    27  var (
    28  	// ErrInputValidation is returned when the input parameters failed validation
    29  	ErrInputValidation = errors.New("input validation error")
    30  )
    31  
    32  // Error parses an error from the response
    33  func (i *iam) Error(r *http.Response) error {
    34  	var e Error
    35  
    36  	var body []byte
    37  
    38  	body, err := ioutil.ReadAll(r.Body)
    39  	if err != nil {
    40  		i.Log(r.Request.Context()).Errorf("reading error response body: %s", err)
    41  		e.StatusCode = r.StatusCode
    42  		e.Title = "Failed to read error body"
    43  		e.Detail = err.Error()
    44  		return &e
    45  	}
    46  
    47  	if err := json.Unmarshal(body, &e); err != nil {
    48  		i.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err)
    49  		e.Title = "Failed to unmarshal error body"
    50  		e.Detail = err.Error()
    51  	}
    52  
    53  	e.StatusCode = r.StatusCode
    54  
    55  	return &e
    56  }
    57  
    58  func (e *Error) Error() string {
    59  	msg, err := json.MarshalIndent(e, "", "\t")
    60  	if err != nil {
    61  		return fmt.Sprintf("error marshaling API error: %s", err)
    62  	}
    63  	return fmt.Sprintf("API error: \n%s", msg)
    64  }
    65  
    66  // Is handles error comparisons
    67  func (e *Error) Is(target error) bool {
    68  	var t *Error
    69  	if !errors.As(target, &t) {
    70  		return false
    71  	}
    72  
    73  	if e == t {
    74  		return true
    75  	}
    76  
    77  	if e.StatusCode != t.StatusCode {
    78  		return false
    79  	}
    80  
    81  	return e.Error() == t.Error()
    82  }