github.com/sap/cf-mta-plugin@v2.6.3+incompatible/clients/baseclient/client_error.go (about) 1 package baseclient 2 3 import ( 4 "bytes" 5 "fmt" 6 7 strfmt "github.com/go-openapi/strfmt" 8 9 "github.com/go-openapi/runtime" 10 ) 11 12 type ClientError struct { 13 Code int 14 Status string 15 Description interface{} 16 } 17 18 func (ce *ClientError) Error() string { 19 return fmt.Sprintf("%s (status %d): %v ", ce.Status, ce.Code, ce.Description) 20 } 21 22 func NewClientError(err error) error { 23 if err == nil { 24 return nil 25 } 26 ae, ok := err.(*runtime.APIError) 27 if ok { 28 response := ae.Response.(runtime.ClientResponse) 29 return &ClientError{Code: ae.Code, Status: response.Message(), Description: response.Message()} 30 } 31 response, ok := err.(*ErrorResponse) 32 if ok { 33 return &ClientError{Code: response.Code, Status: response.Status, Description: response.Payload} 34 } 35 return err 36 } 37 38 func BuildErrorResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { 39 result := &ErrorResponse{ 40 Code: response.Code(), 41 Status: response.Message(), // this isn't the body! 42 } 43 if err := result.readResponse(response, consumer, formats); err != nil { 44 return err 45 } 46 return result 47 } 48 49 // ErrorResponse handles error cases 50 type ErrorResponse struct { 51 Code int 52 Status string 53 Payload string 54 } 55 56 func (ce *ErrorResponse) Error() string { 57 return fmt.Sprintf("%s (status %d): %v ", ce.Status, ce.Code, ce.Payload) 58 } 59 60 func (o *ErrorResponse) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { 61 buf := new(bytes.Buffer) 62 _, err := buf.ReadFrom(response.Body()) 63 if err != nil { 64 return runtime.NewAPIError("unknown error", response, response.Code()) 65 } 66 o.Payload = buf.String() 67 68 return nil 69 }