-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror_handler.go
76 lines (61 loc) · 1.77 KB
/
error_handler.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
package resozyme
import (
"errors"
"fmt"
"net/http"
)
// ErrorHandler is an error handler interface.
type ErrorHandler interface {
// IsError checks whether the given resource has the error.
IsError(resc Resource) bool
// HandleError transforms the resource that has the error to another resource
// that represents the error.
HandleError(resc Resource, w http.ResponseWriter, r *http.Request) Resource
}
// ErrorResource is an resource to represent the error.
type ErrorResource struct {
*Base
view *ErrorView
}
// ErrorView is a view for the error.
type ErrorView struct {
Message string `json:"message"`
}
// View implements resource.Resource.
func (resc *ErrorResource) View() interface{} {
return resc.view
}
// Href implements resource.Resource.
// This method returns the dummy URL contains the status code.
func (resc *ErrorResource) Href() string {
return fmt.Sprintf("/errors/%d", resc.Code())
}
// ExposedErrorHandler is an ErrorHandler.
// [NOTICE] This handler exposes the raw error message to the response view.
type ExposedErrorHandler struct {
Renderer Renderer
}
// IsError implements resource.ErrorHandler.
func (eh *ExposedErrorHandler) IsError(resc Resource) bool {
return resc.Code() >= 400
}
// HandleError implements resource.ErrorHandler.
func (eh *ExposedErrorHandler) HandleError(resc Resource, w http.ResponseWriter, r *http.Request) Resource {
code := resc.Code()
err := resc.Error()
// Set general status text if no error set.
if err == nil {
err = errors.New(http.StatusText(code))
}
errResc := &ErrorResource{
Base: NewBase(r.Context()),
view: &ErrorView{},
}
errResc.SetCode(code)
errResc.view.Message = err.Error()
errResc.SetRenderer(eh.Renderer)
for k, v := range resc.Header() {
errResc.Header()[k] = v
}
return errResc
}