-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttperror.go
64 lines (55 loc) · 1.22 KB
/
httperror.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"fmt"
"io"
"net/http"
"strconv"
)
func checkResponseError(resp *http.Response) error {
category := strconv.Itoa(resp.StatusCode)[0]
switch category {
case '5':
return newServerError(resp)
case '4':
return newClientError(resp)
case '2':
return nil
default:
return newHTTPError(resp)
}
}
// HTTPError represents a server or client error in response.
type HTTPError struct {
Code int
Header http.Header
Message string
}
func newHTTPError(resp *http.Response) *HTTPError {
body, err := io.ReadAll(resp.Body)
message := string(body)
if err != nil {
message = "incomplete: " + message
}
return &HTTPError{
Code: resp.StatusCode,
Header: resp.Header,
Message: message,
}
}
func (e *HTTPError) Error() string {
return fmt.Sprintf("HTTP error; code: %d, message: %s", e.Code, e.Message)
}
// ServerError wraps the error returned to an Efes request.
type ServerError struct {
*HTTPError
}
func newServerError(resp *http.Response) *ServerError {
return &ServerError{newHTTPError(resp)}
}
// ClientError wraps the error returned to an Efes request.
type ClientError struct {
*HTTPError
}
func newClientError(resp *http.Response) *ClientError {
return &ClientError{newHTTPError(resp)}
}