Skip to content

Commit

Permalink
chore(recovery): support custom recovery
Browse files Browse the repository at this point in the history
co-author: @timohuovinen

fix #42
  • Loading branch information
appleboy committed Sep 15, 2022
1 parent 51843d4 commit 9334b16
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion zap.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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()
Expand Down

0 comments on commit 9334b16

Please sign in to comment.