Skip to content

richzw/gin-error

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

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"
)
var BadRequestErr = fmt.Errorf("bad request error")

func main() {
    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"
)
var BadRequestErr = fmt.Errorf("bad request error")

func main() {
    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

License

Stars

Watchers

Forks

Packages

No packages published

Languages