gin-error-handler/handler.go

33 lines
932 B
Go

package handler
import "github.com/gin-gonic/gin"
// This is essentially the same as [gin.HandlerFunc], but allows returning
// an error. This allows for the more idiomatic use:
//
// func UserHandler (c *gin.Context) error {
// user, err := db.GetUser(c.Get("user"))
// if err != nil {
// return err
// }
// c.JSON(200, user)
// }
type HandlerWithError func(c *gin.Context) error
// Allows you to actually use a [HandlerWithError] as a [gin.HandlerFunc].
// If an error is returned, it adds it to the context with c.Error(err).
// This needs to be handled with a middleware, such as [ErrorMiddleware]
//
// Usage:
//
// c.GET("/user", HandlerWithErrorWrapper(UserHandler))
func HandlerWithErrorWrapper(h HandlerWithError) gin.HandlerFunc {
return func(c *gin.Context) {
err := h(c)
if err != nil {
// We shouldn't process more handlers if there was an error
c.Abort()
c.Error(err)
}
}
}