go-fiber: How to adjust the response message inside the recover middleware
06:47 27 Jun 2025

go-fiber comes with a middleware to recover from panic. But I don't want to expose internals, so how can I adjust the message returned to the client? Or is this middleware not made for this - if so, what would be the proper way to handle this?

import (
    "fmt"
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/recover"
)

func main() {
    app := fiber.New()
    app.Get("/", recover.New(recover.Config{
        Next:             nil,
        EnableStackTrace: true,
        // Not really the proper location, but the only one I've got to handle a recovery from panic 
        StackTraceHandler: func(c *fiber.Ctx, e any) {
            fmt.Printf("error: %s\n", e)
            if err := c.SendString("I'll never be shown"); err != nil { // won't have any effect, probably b/c the response is already set
                fmt.Printf("couldn't send error override: %s\n", err)
            }
        },
    }), func(c *fiber.Ctx) error {
        panic("test-panic") // I don't want to see that message on client-side
    })
    _ = app.Listen(":3000")
}

curl -X GET http://localhost:3000 will receive "test-panic", not my override.

Of course, I could just go with this instead:

func(ctx *fiber.Ctx) (err error) {
    defer func() {
        if rec := recover(); rec != nil {
            fmt.Printf("error: %s\n", rec)
            err = fiber.NewError(fiber.StatusInternalServerError, "Unexpected error.")
        }
    }()
    return ctx.Next()
}

But then, what's the purpose of fiber's recover middleware?

go go-fiber