Closed TanmoySG closed 1 year ago
https://strapengine.com/build-a-custom-jwt-go-fiber-middleware/
Based on above guide created a middleware to recover from panic based on fiber/recover
middleware (kind of copied).
```go package handlePanic import ( "net/http" "github.com/gofiber/fiber/v2" ) type Config struct { Next func(c *fiber.Ctx) bool // if true skip middleware SendMessage bool // if true sends message, default: true Message string // message to send ExitHandler func(c *fiber.Ctx) // additonal handling if any } // ConfigDefault is the default config var ConfigDefault = Config{ Next: nil, SendMessage: true, Message: "go panicked", ExitHandler: nil, } func configDefault(config ...Config) Config { if len(config) < 1 { return ConfigDefault } cfg := config[0] return cfg } func New(config ...Config) fiber.Handler { cfg := configDefault(config...) return func(c *fiber.Ctx) (err error) { if cfg.Next != nil && cfg.Next(c) { return c.Next() } defer func() { if r := recover(); r != nil { if cfg.SendMessage { c.Status(http.StatusInternalServerError) c.Send([]byte(cfg.Message)) cfg.ExitHandler(c) } } }() return c.Next() } } ```
```go hpCfg := handlePanic.ConfigDefault hpCfg.ExitHandler = func(c *fiber.Ctx){ CleanExit(ws.data) } hpCfg.Message = "panic created" app := fiber.New() app.Use(logger.New()) app.Use(handlePanic.New(hpCfg)) ```
https://medium.com/swlh/simple-guide-to-panic-handling-and-recovery-in-golang-72d6181ae3e8