Skip to content

RecoveryWithWriter takes mulitple RecoveryFuncs but only applies the first  #4044

@nesselchen

Description

@nesselchen

Description

RecoveryWithWritter has signature func(w io.Writer, recovery ...gin.RecoveryFunc) but only applies the first func from recovery.
If no RecoveryFuncs were passed, it uses the defaultHandleRecovery func.

If I want to register multiple RecoveryFuncs, it would seem plausible to apply them all at once, but with this implementation most would get discarded silently. Additionally, this results in a panicking request returning code 200 instead of the pre-configured code 500.

I don't see why it couldn't allow multiple RecoveryFuncs with each handling the error separately. Alternatively I would appreciate it if the documentation gave hints to this being the intended behavior.

How to reproduce

Here's the excerpt from the gin package (recover.go:43)

// RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.
func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc {
	if len(recovery) > 0 {
		return CustomRecoveryWithWriter(out, recovery[0])
	}
	return CustomRecoveryWithWriter(out, defaultHandleRecovery)
}

Expectations

func PrintErr(_ *gin.Context, err any) {
  if err != nil {
    fmt.Println(err)
  }
}

func Abort(ctx *gin.Context, _ any) {
  ctx.AbortWithStatus(500)
}

// ...

router.Use(RecoveryWithWriter(logger, PrintErr, Abort)) // -> should print the err and abort the request

## Actual result

Under the current implementation only the error would get logged, with the request still returning 200 after recovering.

## Environment

- go version: go1.22.6
- gin version (or commit ref):	github.com/gin-gonic/gin v1.9.1
- operating system: macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions