2022-10-25 17:32:46 +03:00
|
|
|
package v1
|
|
|
|
|
|
|
|
import (
|
2022-10-26 14:58:32 +03:00
|
|
|
"bytes"
|
2022-10-25 17:32:46 +03:00
|
|
|
"encoding/json"
|
2022-10-26 10:54:54 +03:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
2022-10-25 17:32:46 +03:00
|
|
|
)
|
|
|
|
|
2022-10-26 14:58:32 +03:00
|
|
|
var defaultErrorMessage = "internal http client error"
|
|
|
|
var internalServerError = "internal server error"
|
2022-10-25 17:32:46 +03:00
|
|
|
|
|
|
|
type httpClientError struct {
|
2022-10-26 14:58:32 +03:00
|
|
|
ErrorMsg string
|
|
|
|
BaseError error
|
|
|
|
LimitedResponse io.Reader
|
2022-10-25 17:32:46 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (err *httpClientError) Unwrap() error {
|
|
|
|
return err.BaseError
|
|
|
|
}
|
|
|
|
|
2022-10-26 14:58:32 +03:00
|
|
|
func (err *httpClientError) Is(target error) bool {
|
|
|
|
return errors.As(target, &err)
|
|
|
|
}
|
|
|
|
|
2022-10-25 17:32:46 +03:00
|
|
|
func (err *httpClientError) Error() string {
|
|
|
|
message := defaultErrorMessage
|
|
|
|
|
|
|
|
if err.BaseError != nil {
|
2022-10-26 10:54:54 +03:00
|
|
|
message = fmt.Sprintf("%s - %s", defaultErrorMessage, err.BaseError.Error())
|
2022-10-25 17:32:46 +03:00
|
|
|
}
|
|
|
|
|
2022-10-26 10:54:54 +03:00
|
|
|
if len(err.ErrorMsg) > 0 {
|
2022-10-25 17:32:46 +03:00
|
|
|
message = err.ErrorMsg
|
|
|
|
}
|
|
|
|
|
|
|
|
return message
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCriticalHTTPError(err error) error {
|
|
|
|
return &httpClientError{BaseError: err}
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewAPIClientError(responseBody []byte) error {
|
|
|
|
var data map[string]interface{}
|
|
|
|
var message string
|
|
|
|
|
|
|
|
if len(responseBody) == 0 {
|
|
|
|
message = internalServerError
|
|
|
|
} else {
|
|
|
|
if err := json.Unmarshal(responseBody, &data); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
values := data["errors"].([]interface{})
|
|
|
|
message = values[0].(string)
|
|
|
|
}
|
|
|
|
|
|
|
|
return &httpClientError{ErrorMsg: message}
|
2022-10-26 10:54:54 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewServerError(response *http.Response) error {
|
|
|
|
var data []byte
|
2022-10-26 14:58:32 +03:00
|
|
|
body, err := buildLimitedRawResponse(response)
|
2022-10-26 10:54:54 +03:00
|
|
|
if err == nil {
|
|
|
|
data = body
|
|
|
|
}
|
|
|
|
|
|
|
|
err = NewAPIClientError(data)
|
|
|
|
var serverError *httpClientError
|
|
|
|
|
|
|
|
if errors.As(err, &serverError) {
|
2022-10-26 14:58:32 +03:00
|
|
|
serverError.LimitedResponse = bytes.NewBuffer(body)
|
2022-10-26 10:54:54 +03:00
|
|
|
return serverError
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|