github.com/hanks177/podman/v4@v4.1.3-0.20220613032544-16d90015bc83/pkg/bindings/errors.go (about)

     1  package bindings
     2  
     3  import (
     4  	"encoding/json"
     5  	"io/ioutil"
     6  
     7  	"github.com/hanks177/podman/v4/pkg/errorhandling"
     8  	"github.com/pkg/errors"
     9  )
    10  
    11  var (
    12  	ErrNotImplemented = errors.New("function not implemented")
    13  )
    14  
    15  func handleError(data []byte, unmarshalErrorInto interface{}) error {
    16  	if err := json.Unmarshal(data, unmarshalErrorInto); err != nil {
    17  		return err
    18  	}
    19  	return unmarshalErrorInto.(error)
    20  }
    21  
    22  // Process drains the response body, and processes the HTTP status code
    23  // Note: Closing the response.Body is left to the caller
    24  func (h APIResponse) Process(unmarshalInto interface{}) error {
    25  	return h.ProcessWithError(unmarshalInto, &errorhandling.ErrorModel{})
    26  }
    27  
    28  // ProcessWithError drains the response body, and processes the HTTP status code
    29  // Note: Closing the response.Body is left to the caller
    30  func (h APIResponse) ProcessWithError(unmarshalInto interface{}, unmarshalErrorInto interface{}) error {
    31  	data, err := ioutil.ReadAll(h.Response.Body)
    32  	if err != nil {
    33  		return errors.Wrap(err, "unable to process API response")
    34  	}
    35  	if h.IsSuccess() || h.IsRedirection() {
    36  		if unmarshalInto != nil {
    37  			return json.Unmarshal(data, unmarshalInto)
    38  		}
    39  		return nil
    40  	}
    41  
    42  	if h.IsConflictError() {
    43  		return handleError(data, unmarshalErrorInto)
    44  	}
    45  
    46  	// TODO should we add a debug here with the response code?
    47  	return handleError(data, &errorhandling.ErrorModel{})
    48  }
    49  
    50  func CheckResponseCode(inError error) (int, error) {
    51  	switch e := inError.(type) {
    52  	case *errorhandling.ErrorModel:
    53  		return e.Code(), nil
    54  	case *errorhandling.PodConflictErrorModel:
    55  		return e.Code(), nil
    56  	default:
    57  		return -1, errors.New("is not type ErrorModel")
    58  	}
    59  }