From 9334b16ac88c0f13a0c39bbcad0ced641bca381b Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Thu, 15 Sep 2022 13:46:03 +0800 Subject: [PATCH] chore(recovery): support custom recovery co-author: @timohuovinen fix https://github.com/gin-contrib/zap/pull/42 --- zap.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/zap.go b/zap.go index 28451dc..bfaf75f 100644 --- a/zap.go +++ b/zap.go @@ -93,12 +93,25 @@ func GinzapWithConfig(logger *zap.Logger, conf *Config) gin.HandlerFunc { } } +func defaultHandleRecovery(c *gin.Context, err interface{}) { + c.AbortWithStatus(http.StatusInternalServerError) +} + // RecoveryWithZap returns a gin.HandlerFunc (middleware) // that recovers from any panics and logs requests using uber-go/zap. // All errors are logged using zap.Error(). // stack means whether output the stack info. // The stack info is easy to find where the error occurs but the stack info is too large. func RecoveryWithZap(logger *zap.Logger, stack bool) gin.HandlerFunc { + return CustomRecoveryWithZap(logger, stack, defaultHandleRecovery) +} + +// CustomRecoveryWithZap returns a gin.HandlerFunc (middleware) with a custom recovery handler +// that recovers from any panics and logs requests using uber-go/zap. +// All errors are logged using zap.Error(). +// stack means whether output the stack info. +// The stack info is easy to find where the error occurs but the stack info is too large. +func CustomRecoveryWithZap(logger *zap.Logger, stack bool, recovery gin.RecoveryFunc) gin.HandlerFunc { return func(c *gin.Context) { defer func() { if err := recover(); err != nil { @@ -139,7 +152,7 @@ func RecoveryWithZap(logger *zap.Logger, stack bool) gin.HandlerFunc { zap.String("request", string(httpRequest)), ) } - c.AbortWithStatus(http.StatusInternalServerError) + recovery(c, err) } }() c.Next()