✨ Add middleware
This commit is contained in:
parent
447f3b38ef
commit
4c635ffbe8
4 changed files with 147 additions and 2 deletions
41
middleware.go
Normal file
41
middleware.go
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
rErrors "codeberg.org/danjones000/responsable-errors"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func ErrorMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Next()
|
||||
err := c.Errors.Last()
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var re rErrors.ResponsableError
|
||||
errors.As(err, &re)
|
||||
for _, err = range c.Errors {
|
||||
errors.As(err, &re)
|
||||
if re != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// @todo we need to add some way to do custom handling
|
||||
|
||||
// @todo Refactor this with 👆
|
||||
if re == nil {
|
||||
switch err.Type {
|
||||
case gin.ErrorTypePrivate:
|
||||
re = rErrors.NewInternalError("%w", err)
|
||||
default:
|
||||
re = rErrors.NewBadRequest("%w", err)
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(re.GetStatus(), gin.H{"error": re.GetMsg()})
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue