-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror.go
49 lines (40 loc) · 1.2 KB
/
error.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package klient
import (
"errors"
"fmt"
"io"
"net/http"
)
var (
ErrCreateRequest = errors.New("failed to create request")
ErrRequest = errors.New("failed to do request")
ErrResponseFuncNil = errors.New("response function is nil")
ErrRequesterNil = errors.New("requester is nil")
)
type ResponseError struct {
StatusCode int
Body string
RequestID string
}
func (e *ResponseError) Error() string {
if e.RequestID == "" {
return fmt.Sprintf("unexpected response [%d]: %s", e.StatusCode, e.Body)
}
return fmt.Sprintf("unexpected response [%d] with request id [%s]: %s", e.StatusCode, e.RequestID, e.Body)
}
// ErrResponse returns an error with the limited response body.
func ErrResponse(resp *http.Response) error {
partialBody, _ := io.ReadAll(io.LimitReader(resp.Body, ResponseErrLimit))
return &ResponseError{
StatusCode: resp.StatusCode,
Body: string(partialBody),
RequestID: resp.Header.Get("X-Request-Id"),
}
}
// UnexpectedResponse returns an error if the response status code is not 2xx with calling ResponseError.
func UnexpectedResponse(resp *http.Response) error {
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return ErrResponse(resp)
}
return nil
}