-
Notifications
You must be signed in to change notification settings - Fork 0
/
panic.go
55 lines (51 loc) · 1.37 KB
/
panic.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
package middleware
import (
"encoding/json"
"net/http"
"runtime/debug"
g "github.com/maktoobgar/go_template/internal/global"
"github.com/maktoobgar/go_template/pkg/errors"
"github.com/maktoobgar/go_template/pkg/translator"
)
type PanicResponse struct {
Message string `json:"message"`
Action int `json:"action"`
Code int `json:"code"`
Errors any `json:"errors"`
}
func Panic(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
translate := r.Context().Value("translate").(translator.TranslatorFunc)
defer func() {
errInterface := recover()
if errInterface == nil {
return
}
if err, ok := errInterface.(error); ok && errors.IsServerError(err) {
code, action, message, errors := errors.HttpError(err)
res := PanicResponse{
Message: message,
Action: action,
Code: code,
Errors: errors,
}
resBytes, _ := json.Marshal(res)
w.WriteHeader(code)
w.Write(resBytes)
} else {
stack := string(debug.Stack())
g.Logger.Panic(errInterface, r, stack)
res := PanicResponse{
Message: translate("InternalServerError"),
Action: errors.Report,
Code: http.StatusInternalServerError,
Errors: nil,
}
resBytes, _ := json.Marshal(res)
w.WriteHeader(res.Code)
w.Write(resBytes)
}
}()
next.ServeHTTP(w, r)
})
}