-
Notifications
You must be signed in to change notification settings - Fork 0
/
h_onerror.go
68 lines (58 loc) · 1.48 KB
/
h_onerror.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
package webutil
import (
"context"
"fmt"
"net/http"
"github.com/noypi/router"
)
type _errorKey int
const (
ErrorKey _errorKey = iota
ErrorInfo
)
func AddError(ctx context.Context, err error) {
c := ToStore(ctx)
c.Set(ErrorKey, err)
}
func GetErrorInfo(ctx context.Context) interface{} {
c := ToStore(ctx)
o, _ := c.Get(ErrorInfo)
return o
}
func ifHasErrorRedirect(w http.ResponseWriter, r *http.Request, theURL string, moreinfo interface{}) {
ctx := router.ContextW(w)
c := ToStore(ctx)
err, hasError := c.Get(ErrorKey)
if hasError {
if nil != moreinfo {
c.Set(ErrorInfo, moreinfo)
}
ctx.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s?error=%v", theURL, err))
ctx.Abort()
ERR := router.GetErrLog(ctx)
ERR.Ln("err=", err)
ERR.PrintStackTrace(20)
return
}
}
func IfHasErrorRedirect(theURL string, moreinfo interface{}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ifHasErrorRedirect(w, r, theURL, moreinfo)
}
}
func OnErrorRedirect(h http.HandlerFunc, theURL string, moreinfo interface{}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
ifHasErrorRedirect(w, r, theURL, moreinfo)
}
}
func OnErrorGotoReferrer(h http.HandlerFunc, moreinfo interface{}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
theURL := r.URL.Path
if 0 < len(r.URL.RawQuery) {
theURL += "?" + r.URL.RawQuery
}
ifHasErrorRedirect(w, r, theURL, moreinfo)
}
}