TanmoySG / wunderDB

A micro JSON-based Data Store inspired by MongoDB.
http://wdb.tanmoysg.com/api/
Apache License 2.0
12 stars 0 forks source link

[Development] Handle Panic and Recovery #87

Closed TanmoySG closed 1 year ago

TanmoySG commented 1 year ago

https://medium.com/swlh/simple-guide-to-panic-handling-and-recovery-in-golang-72d6181ae3e8

TanmoySG commented 1 year ago

Middlewares

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).

Custom Middleware

```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() } } ```

Usage

```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)) ```