Skip to content

Repository files navigation

Gin Handle Error Middleware

Gin Handle Error Middleware is one middleware for Gin framework that you could handle errors in middleware, so you could NOT do error handling within each handler.

Installation

Download and install using go module:

go get github.com/richzw/gin-error

Import it in your code:

import "github.com/richzw/gin-error"

Example

  • Map error to one status code
import (
"github.com/richzw/gin-error""github.com/gin-gonic/gin"
)
varBadRequestErr=fmt.Errorf("bad request error")
funcmain() {
r:=gin.Default()
r.Use(err.Error(err.NewErrMap(BadRequestErr).StatusCode(http.StatusBadRequest)))
r.GET("/test", func(c*gin.Context) {
c.Error(BadRequestErr)
})
r.Run()
}
  • Map error to the response
import (
"github.com/richzw/gin-error""github.com/gin-gonic/gin"
)
varBadRequestErr=fmt.Errorf("bad request error")
funcmain() {
r:=gin.Default()
r.Use(err.Error(
err.NewErrMap(BadRequestErr).Response(func(c*gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": BadRequestErr.Error()})
})))
r.GET("/test", func(c*gin.Context) {
c.Error(BadRequestErr)
})
r.Run()
}

License

Gin Handle Error Middleware is licensed under the MIT.

About

No description, website, or topics provided.

Resources

Stars

4 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages