/
errors.go
81 lines (69 loc) · 2.06 KB
/
errors.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package httpsimp
import (
"fmt"
)
type wrapperError struct {
Method string
Path string
Cause error
}
func (err *wrapperError) Error() string {
if err.Path != "" {
return fmt.Sprintf("%s %s: %v", err.Method, err.Path, err.Cause)
} else {
return fmt.Sprintf("%s: %v", err.Method, err.Cause)
}
}
type responseError struct {
StatusCode int
ContentType string
WantedContentType string
ContentTypeOK bool
Body interface{}
DecodingError error
}
func (err *responseError) Error() string {
if !err.ContentTypeOK {
if err.DecodingError != nil {
return fmt.Sprintf("HTTP %d, unexpected response of type %v, wanted %v; error decoding response body: %v", err.StatusCode, err.ContentType, err.WantedContentType, err.DecodingError)
} else if err.Body != nil {
return fmt.Sprintf("HTTP %d, unexpected response of type %v, wanted %v: %v", err.StatusCode, err.ContentType, err.WantedContentType, err.Body)
} else {
return fmt.Sprintf("HTTP %d, unexpected response type %v, wanted %v", err.StatusCode, err.ContentType, err.WantedContentType)
}
} else {
if err.DecodingError != nil {
return fmt.Sprintf("HTTP %d, error decoding %v response: %v", err.StatusCode, err.ContentType, err.DecodingError)
} else if err.Body != nil {
return fmt.Sprintf("HTTP %d, %v response: %v", err.StatusCode, err.ContentType, err.Body)
} else {
return fmt.Sprintf("HTTP %d, %v response", err.StatusCode, err.ContentType)
}
}
}
func getResponseError(err error) *responseError {
if e, ok := err.(*wrapperError); ok {
err = e.Cause
}
e, _ := err.(*responseError)
return e
}
/*
StatusCode returns the HTTP status code carried by the given error.
Returns 0 if the error is not produced by a body parser function.
*/
func StatusCode(err error) int {
if e := getResponseError(err); e != nil {
return e.StatusCode
} else {
return 0
}
}
func Is5xx(err error) bool {
code := StatusCode(err)
return (code != 0) && (code >= 500 && code <= 599)
}
func Is4xx(err error) bool {
code := StatusCode(err)
return (code != 0) && (code >= 400 && code <= 499)
}