2022-03-18 21:09:56 +00:00
|
|
|
package twitch
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
2023-07-21 18:37:20 +00:00
|
|
|
// HTTPError represents an HTTP error containing the response body (or
|
|
|
|
// the wrapped error occurred while readiny the body) and the status
|
|
|
|
// code returned by the server
|
|
|
|
type HTTPError struct {
|
|
|
|
Body []byte
|
|
|
|
Code int
|
|
|
|
Err error
|
2022-03-18 21:09:56 +00:00
|
|
|
}
|
|
|
|
|
2023-07-21 18:37:20 +00:00
|
|
|
// ErrAnyHTTPError can be used in errors.Is() to match an HTTPError
|
|
|
|
// with any status code
|
|
|
|
var ErrAnyHTTPError = newHTTPError(0, nil, nil)
|
2022-03-18 21:09:56 +00:00
|
|
|
|
2023-07-21 18:37:20 +00:00
|
|
|
func newHTTPError(status int, body []byte, wrappedErr error) HTTPError {
|
|
|
|
return HTTPError{
|
|
|
|
Body: body,
|
|
|
|
Code: status,
|
|
|
|
Err: wrappedErr,
|
2022-03-18 21:09:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-21 18:37:20 +00:00
|
|
|
// Error implements the error interface and returns a formatted version
|
|
|
|
// of the error including the body, might therefore leak confidential
|
|
|
|
// information when included in the response body
|
|
|
|
func (h HTTPError) Error() string {
|
|
|
|
selfE := fmt.Sprintf("unexpected status %d", h.Code)
|
|
|
|
if h.Body != nil {
|
|
|
|
selfE = fmt.Sprintf("%s (%s)", selfE, h.Body)
|
2022-03-18 21:09:56 +00:00
|
|
|
}
|
|
|
|
|
2023-07-21 18:37:20 +00:00
|
|
|
if h.Err == nil {
|
2022-03-18 21:09:56 +00:00
|
|
|
return selfE
|
|
|
|
}
|
|
|
|
|
2023-07-21 18:37:20 +00:00
|
|
|
return fmt.Sprintf("%s: %s", selfE, h.Err)
|
2022-03-18 21:09:56 +00:00
|
|
|
}
|
|
|
|
|
2023-07-21 18:37:20 +00:00
|
|
|
// Is checks whether the given error is an HTTPError and the status
|
|
|
|
// code matches the given error
|
|
|
|
func (h HTTPError) Is(target error) bool {
|
|
|
|
ht, ok := target.(HTTPError)
|
2022-03-18 21:09:56 +00:00
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2023-07-21 18:37:20 +00:00
|
|
|
return ht.Code == 0 || ht.Code == h.Code
|
2022-03-18 21:09:56 +00:00
|
|
|
}
|
|
|
|
|
2023-07-21 18:37:20 +00:00
|
|
|
// Unwrap returns the wrapped error occurred when reading the body
|
|
|
|
func (h HTTPError) Unwrap() error {
|
|
|
|
return h.Err
|
2022-03-18 21:09:56 +00:00
|
|
|
}
|