github.com/mondo192/jfrog-client-go@v1.0.0/utils/errorutils/errorutils.go (about) 1 package errorutils 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "errors" 7 "fmt" 8 "io" 9 "net/http" 10 ) 11 12 // Error modes (how should the application behave when the CheckError function is invoked): 13 type OnErrorHandler func(error) error 14 15 var CheckError = func(err error) error { 16 return err 17 } 18 19 func CheckErrorf(format string, a ...interface{}) error { 20 if len(a) > 0 { 21 return CheckError(fmt.Errorf(format, a...)) 22 } 23 return CheckError(errors.New(format)) 24 } 25 26 // Check expected status codes and return error if needed 27 func CheckResponseStatus(resp *http.Response, expectedStatusCodes ...int) error { 28 for _, statusCode := range expectedStatusCodes { 29 if statusCode == resp.StatusCode { 30 return nil 31 } 32 } 33 // Add resp.Body to error response if exists 34 errorBody, _ := io.ReadAll(resp.Body) 35 return CheckError(GenerateResponseError(resp.Status, string(errorBody))) 36 } 37 38 // Check expected status codes and return error with body if needed 39 // We use body variable that was saved outside the resp.body object, 40 // Instead of resp.Body because resp.body disappears after resp.body.Close() 41 func CheckResponseStatusWithBody(resp *http.Response, body []byte, expectedStatusCodes ...int) error { 42 for _, statusCode := range expectedStatusCodes { 43 if statusCode == resp.StatusCode { 44 return nil 45 } 46 } 47 return CheckError(GenerateResponseError(resp.Status, generateErrorString(body))) 48 } 49 50 func GenerateResponseError(status, body string) error { 51 responseErrString := "server response: " + status 52 if body != "" { 53 responseErrString = responseErrString + "\n" + body 54 } 55 return fmt.Errorf(responseErrString) 56 } 57 58 func generateErrorString(bodyArray []byte) string { 59 var content bytes.Buffer 60 if err := json.Indent(&content, bodyArray, "", " "); err != nil { 61 return string(bodyArray) 62 } 63 return content.String() 64 }