-
Notifications
You must be signed in to change notification settings - Fork 6
/
error.go
58 lines (48 loc) · 1.61 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
package babyapi
import (
"fmt"
"net/http"
"github.com/go-chi/render"
)
var ErrNotFoundResponse = &ErrResponse{HTTPStatusCode: http.StatusNotFound, StatusText: "Resource not found."}
var ErrMethodNotAllowedResponse = &ErrResponse{HTTPStatusCode: http.StatusMethodNotAllowed, StatusText: "Method not allowed."}
var ErrForbidden = &ErrResponse{HTTPStatusCode: http.StatusForbidden, StatusText: "Forbidden"}
// ErrResponse is an error that implements Renderer to be used in HTTP response
type ErrResponse struct {
Err error `json:"-"`
HTTPStatusCode int `json:"-"`
StatusText string `json:"status"` // user-level status message
AppCode int64 `json:"code,omitempty"` // application-specific error code
ErrorText string `json:"error,omitempty"` // application-level error message, for debugging
}
func (e *ErrResponse) Error() string {
return fmt.Sprintf("unexpected response with text: %s", e.StatusText)
}
func (e *ErrResponse) Render(_ http.ResponseWriter, r *http.Request) error {
render.Status(r, e.HTTPStatusCode)
return nil
}
func ErrRender(err error) *ErrResponse {
return &ErrResponse{
Err: err,
HTTPStatusCode: 422,
StatusText: "Error rendering response.",
ErrorText: err.Error(),
}
}
func ErrInvalidRequest(err error) *ErrResponse {
return &ErrResponse{
Err: err,
HTTPStatusCode: 400,
StatusText: "Invalid request.",
ErrorText: err.Error(),
}
}
func InternalServerError(err error) *ErrResponse {
return &ErrResponse{
Err: err,
HTTPStatusCode: 500,
StatusText: "Server Error.",
ErrorText: err.Error(),
}
}