From 80caeeb8ca9930c9becf54dde286b94fe7118929 Mon Sep 17 00:00:00 2001 From: TianJun Date: Wed, 28 Apr 2021 17:18:23 +0800 Subject: [PATCH] =?UTF-8?q?=E5=85=A8=E5=B1=80=E5=BC=82=E5=B8=B8=E6=8D=95?= =?UTF-8?q?=E6=8D=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/middleware/gin_panic.go | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/middleware/gin_panic.go diff --git a/src/middleware/gin_panic.go b/src/middleware/gin_panic.go new file mode 100644 index 0000000..4c0f7fd --- /dev/null +++ b/src/middleware/gin_panic.go @@ -0,0 +1,38 @@ +package middleware + +import ( + "github.com/gin-gonic/gin" + "lingye-gin/src/config" + "net/http" + "runtime/debug" +) + +func GinPanic(c *gin.Context) { + defer func() { + if r := recover(); r != nil { + // 打印错误堆栈信息 + config.Logger.Printf("panic: %v\n", r) + debug.PrintStack() + // 封装通用json返回 + c.JSON(http.StatusOK, gin.H{ + "code": http.StatusBadRequest, + "msg": errorToString(r), + "data": nil, + }) + //终止后续接口调用,不加的话recover到异常后,还会继续执行接口里后续代码 + c.Abort() + } + }() + // 加载完 defer recover,继续后续接口调用 + c.Next() +} + +// recover错误,转string +func errorToString(r interface{}) string { + switch v := r.(type) { + case error: + return v.Error() + default: + return r.(string) + } +}