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

     1  package edgeworkers
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net/http"
     9  )
    10  
    11  type (
    12  	// Error is an edgeworkers error implementation
    13  	// For details on possible error types, refer to: https://techdocs.akamai.com/edgeworkers/reference/api-errors
    14  	Error struct {
    15  		Type             string     `json:"type,omitempty"`
    16  		Title            string     `json:"title,omitempty"`
    17  		Detail           string     `json:"detail,omitempty"`
    18  		Instance         string     `json:"instance,omitempty"`
    19  		Status           int        `json:"status,omitempty"`
    20  		ErrorCode        string     `json:"errorCode,omitempty"`
    21  		Method           string     `json:"method,omitempty"`
    22  		ServerIP         string     `json:"serverIp,omitempty"`
    23  		ClientIP         string     `json:"clientIp,omitempty"`
    24  		RequestID        string     `json:"requestId,omitempty"`
    25  		RequestTime      string     `json:"requestTime,omitempty"`
    26  		AuthzRealm       string     `json:"authzRealm,omitempty"`
    27  		AdditionalDetail Additional `json:"additionalDetail,omitempty"`
    28  	}
    29  
    30  	// Additional holds request_id for edgekv errors
    31  	Additional struct {
    32  		RequestID string `json:"requestId,omitempty"`
    33  	}
    34  )
    35  
    36  // Error parses an error from the response
    37  func (e *edgeworkers) Error(r *http.Response) error {
    38  	var result Error
    39  	var body []byte
    40  	body, err := ioutil.ReadAll(r.Body)
    41  	if err != nil {
    42  		e.Log(r.Request.Context()).Errorf("reading error response body: %s", err)
    43  		result.Status = r.StatusCode
    44  		result.Title = "Failed to read error body"
    45  		result.Detail = err.Error()
    46  		return &result
    47  	}
    48  
    49  	if err := json.Unmarshal(body, &result); err != nil {
    50  		e.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err)
    51  		result.Title = string(body)
    52  		result.Status = r.StatusCode
    53  	}
    54  	return &result
    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.Status != t.Status {
    77  		return false
    78  	}
    79  
    80  	return e.Error() == t.Error()
    81  }