-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
53 lines (40 loc) · 1.66 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
package servers
import (
"log/slog"
"net/http"
"github.com/relvox/iridescence_go/logging"
)
type BadRequestError string
func ToBadRequestError(err error) BadRequestError { return BadRequestError(err.Error()) }
func (e BadRequestError) Error() string { return string(e) }
type InternalError string
func ToInternalError(err error) InternalError { return InternalError(err.Error()) }
func (e InternalError) Error() string { return string(e) }
type PanicError string
func ToPanicError(err error) PanicError { return PanicError(err.Error()) }
func (e PanicError) Error() string { return string(e) }
func writeErrorResponse(log *slog.Logger, r *http.Request, w http.ResponseWriter, err error) {
switch err.(type) {
case BadRequestError:
log.Error("handler input error", slog.String("url", r.RequestURI), logging.Error(err))
http.Error(w, err.Error(), http.StatusBadRequest)
case PanicError:
log.Error("handler panic", slog.String("url", r.RequestURI), logging.Error(err))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
case InternalError:
log.Error("handler error", slog.String("url", r.RequestURI), logging.Error(err))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
default:
log.Error("unknown error", slog.String("url", r.RequestURI), logging.Error(err))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
func panicRecovery(log *slog.Logger, r *http.Request, w http.ResponseWriter) {
if er := recover(); er != nil {
err, ok := er.(error)
if !ok {
panic(er)
}
writeErrorResponse(log, r, w, ToPanicError(err))
}
}