-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy patherror.go
79 lines (63 loc) · 1.5 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
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
package storm
import (
"fmt"
"net/http"
)
// HTTPError is an error that extends the built-in Go error with status code hinting.
type HTTPError interface {
error
StatusCode() int
}
type RPCError struct {
ExceptionType string
ExceptionMessage string
}
func (RPCError) StatusCode() int {
return http.StatusInternalServerError
}
func (e RPCError) Error() string {
return fmt.Sprintf("%s: %s", e.ExceptionType, e.ExceptionMessage)
}
var _ HTTPError = (*Error)(nil)
// Hint wraps an input error to hint the HTTP status code.
// If err already implements HTTPError then that error is used directly
func Hint(code int, err error) error {
if httpError, ok := err.(HTTPError); ok {
return httpError
}
return &Error{
Message: err.Error(),
Code: code,
}
}
type Error struct {
Message string
Code int
}
func (e *Error) Error() string {
return e.Message
}
func (e *Error) StatusCode() int {
return e.Code
}
type errorResponse struct {
Error string
}
// SendError sends an error back to the client.
// If err implements HTTPError then that status code is used. Otherwise HTTP InternalServerError is sent.
// It delivers the error message as the errorResponse payload.
func SendError(rw http.ResponseWriter, err error) {
var (
code = http.StatusInternalServerError
response = errorResponse{
Error: err.Error(),
}
)
if httpError, ok := err.(HTTPError); ok {
code = httpError.StatusCode()
}
if wr, ok := rw.(*WrappedResponse); ok {
wr.error = err
}
Send(rw, code, &response)
}