Skip to content

Commit 40f1b4f

Browse files
committed
perfect(responseModifyCreater): 优化闭包函数,可以捕捉内层函数的 panic 信息
1 parent 0e05db7 commit 40f1b4f

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

internal/handler/utils.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ import (
1212
"net/http"
1313
"net/http/httputil"
1414
"net/url"
15+
"reflect"
16+
"runtime"
17+
"runtime/debug"
1518
"strconv"
1619
"strings"
1720
"time"
@@ -24,7 +27,19 @@ import (
2427
//
2528
// 将需要修改上游响应的处理器包装成一个 gin.HandlerFunc 处理器
2629
func responseModifyCreater(proxy *httputil.ReverseProxy, modifyResponseFN func(rw *http.Response) error) gin.HandlerFunc {
27-
proxy.ModifyResponse = modifyResponseFN
30+
funcPtr := reflect.ValueOf(modifyResponseFN).Pointer()
31+
funcName := strings.ReplaceAll(runtime.FuncForPC(funcPtr).Name(), "-fm", "")
32+
logging.Debugf("创建响应修改处理器:%s", funcName)
33+
34+
proxy.ModifyResponse = func(rw *http.Response) error {
35+
defer func() {
36+
if r := recover(); r != nil {
37+
logging.Errorf("%s 发生 panic:%s\n%s", funcName, r, string(debug.Stack()))
38+
}
39+
}()
40+
return modifyResponseFN(rw)
41+
}
42+
2843
return func(ctx *gin.Context) {
2944
proxy.ServeHTTP(ctx.Writer, ctx.Request)
3045
}

0 commit comments

Comments
 (0)