errors.go raw

   1  package dns
   2  
   3  import (
   4  	"encoding/json"
   5  	"errors"
   6  	"fmt"
   7  	"io"
   8  	"net/http"
   9  
  10  	"github.com/akamai/AkamaiOPEN-edgegrid-golang/v11/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 a papi 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  // Error parses an error from the response
  32  func (d *dns) Error(r *http.Response) error {
  33  	var e Error
  34  
  35  	var body []byte
  36  
  37  	body, err := io.ReadAll(r.Body)
  38  	if err != nil {
  39  		d.Log(r.Request.Context()).Errorf("reading error response body: %s", err)
  40  		e.StatusCode = r.StatusCode
  41  		e.Title = "Failed to read error body"
  42  		e.Detail = err.Error()
  43  		return &e
  44  	}
  45  
  46  	if err := json.Unmarshal(body, &e); err != nil {
  47  		d.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err)
  48  		e.Title = "Failed to unmarshal error body. DNS API failed. Check details for more information."
  49  		e.Detail = errs.UnescapeContent(string(body))
  50  	}
  51  
  52  	e.StatusCode = r.StatusCode
  53  
  54  	return &e
  55  }
  56  
  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  }
  78