-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
91 lines (73 loc) · 1.77 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
80
81
82
83
84
85
86
87
88
89
90
91
package tanukirpc
import (
"errors"
"fmt"
"log/slog"
"net/http"
)
type ErrorWithStatus interface {
error
Status() int
}
type errorWithStatus struct {
status int
err error
}
func (e *errorWithStatus) Error() string {
return e.err.Error()
}
func (e *errorWithStatus) Status() int {
return e.status
}
func (e *errorWithStatus) Unwrap() error {
return e.err
}
func WrapErrorWithStatus(status int, err error) error {
return &errorWithStatus{status: status, err: err}
}
type ErrorWithRedirect interface {
error
Status() int
Redirect() string
}
type errorWithRedirect struct {
status int
redirect string
}
func (e *errorWithRedirect) Error() string {
return fmt.Sprintf("redirect to %s", e.redirect)
}
func (e *errorWithRedirect) Status() int {
return e.status
}
func (e *errorWithRedirect) Redirect() string {
return e.redirect
}
func ErrorRedirectTo(status int, redirect string) error {
return &errorWithRedirect{status: status, redirect: redirect}
}
type ErrorMessage struct {
Error ErrorBody `json:"error"`
}
type ErrorBody struct {
Message string `json:"message"`
}
type ErrorHooker interface {
OnError(w http.ResponseWriter, req *http.Request, logger *slog.Logger, codec Codec, err error)
}
type errorHooker struct{}
func (e *errorHooker) OnError(w http.ResponseWriter, req *http.Request, logger *slog.Logger, codec Codec, err error) {
var ewr ErrorWithRedirect
if errors.As(err, &ewr) {
http.Redirect(w, req, ewr.Redirect(), ewr.Status())
return
}
var ews ErrorWithStatus
if errors.As(err, &ews) {
w.WriteHeader(ews.Status())
} else {
w.WriteHeader(http.StatusInternalServerError)
logger.ErrorContext(req.Context(), "ocurred internal server error", slog.Any("error", err))
}
codec.Encode(w, req, ErrorMessage{Error: ErrorBody{Message: err.Error()}})
}