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

     1  package appsec
     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  var (
    14  	// ErrBadRequest is returned when a required parameter is missing.
    15  	ErrBadRequest = errors.New("missing argument")
    16  )
    17  
    18  type (
    19  	// Error is an appsec error interface.
    20  	Error struct {
    21  		Type          string `json:"type"`
    22  		Title         string `json:"title"`
    23  		Detail        string `json:"detail"`
    24  		Instance      string `json:"instance,omitempty"`
    25  		BehaviorName  string `json:"behaviorName,omitempty"`
    26  		ErrorLocation string `json:"errorLocation,omitempty"`
    27  		StatusCode    int    `json:"-"`
    28  	}
    29  )
    30  
    31  func (p *appsec) Error(r *http.Response) error {
    32  	var e Error
    33  
    34  	var body []byte
    35  
    36  	body, err := ioutil.ReadAll(r.Body)
    37  	if err != nil {
    38  		p.Log(r.Request.Context()).Errorf("reading error response body: %s", err)
    39  		e.StatusCode = r.StatusCode
    40  		e.Title = "Failed to read error body"
    41  		e.Detail = err.Error()
    42  		return &e
    43  	}
    44  
    45  	if err := json.Unmarshal(body, &e); err != nil {
    46  		p.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err)
    47  		e.Title = "Failed to unmarshal error body. Application Security API failed. Check details for more information."
    48  		e.Detail = errs.UnescapeContent(string(body))
    49  	}
    50  
    51  	e.StatusCode = r.StatusCode
    52  
    53  	return &e
    54  }
    55  
    56  // Error returns a string formatted using a given title, type, and detail information.
    57  func (e *Error) Error() string {
    58  	return fmt.Sprintf("Title: %s; Type: %s; Detail: %s", e.Title, e.Type, e.Detail)
    59  }
    60  
    61  // Is handles error comparisons.
    62  func (e *Error) Is(target error) bool {
    63  	var t *Error
    64  	if !errors.As(target, &t) {
    65  		return false
    66  	}
    67  
    68  	if e == t {
    69  		return true
    70  	}
    71  
    72  	if e.StatusCode != t.StatusCode {
    73  		return false
    74  	}
    75  
    76  	return e.Error() == t.Error()
    77  }