-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors.go
80 lines (72 loc) · 2.08 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
package tea
import (
"fmt"
"net/http"
)
// StatusError creates a response message consisting of the status code
// and the http.StatusText which applies to that code.
//
// This is useful within StatusHandlerFuncs to quickly break out of the
// normal flow of code
//
// Example:
//
// func(w http.ResponseWriter, r *http.Request) (int, interface{}) {
// u, p, ok := r.BasicAuth()
// if !ok {
// return StatusError(StatusUnauthorized)
// }
// }
//
func StatusError(status int) (int, *ErrorResponse) {
return Error(status, http.StatusText(status))
}
// Error creates a response message consisting of the status code
// and the error string provided. The error string will be rendered back
// to the client. This is ideal for client errors where the client should
// be informed of the specific error message.
//
// This is useful within StatusHandlerFuncs to quickly break out of the
// normal flow of code. It also renders the status code in the body of
// the response which is often very helpful for clients.
//
// Example:
//
// func CreateUser(w http.ResponseWriter, r *http.Request) (int, interface{}) {
// // ...
// if req.Name == "" {
// return Error(400, "name is required")
// }
// }
//
func Error(status int, err string) (int, *ErrorResponse) {
return status, &ErrorResponse{
Code: status,
Err: err,
}
}
// Errorf formats the message and returns the *ErrorResponse with the
// formatted message according to package fmt
func Errorf(status int, format string, v ...interface{}) (int, *ErrorResponse) {
return Error(status, fmt.Sprintf(format, v...))
}
// ErrorResponse is a generic response object
type ErrorResponse struct {
Code int `json:"code"`
Err string `json:"error"`
}
func (e ErrorResponse) Error() string {
return e.Err
}
// NotFound is a handler for 404 requests
func NotFound(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
_, msg := StatusError(404)
Responder(w, r, msg)
}
// MethodNotAllowed is a handler for 405 requests
func MethodNotAllowed(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(405)
_, msg := StatusError(405)
Responder(w, r, msg)
}