gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
78.97k stars 8.02k forks source link

How to custom http error handling #1906

Open zxysilent opened 5 years ago

zxysilent commented 5 years ago

Description

How to custom http error handling

Screenshots

eg https://echo.labstack.com/guide/error-handling

guonaihong commented 5 years ago

Use the AbortWithStatusJSON function in gin to achieve echo-like effects.

package main

import (
        "github.com/gin-gonic/gin"
)

func check() gin.HandlerFunc {
        return func(c *gin.Context) {
                if c.Request.URL.Path != "/test" {
                        c.AbortWithStatusJSON(500, gin.H{"message": "path fail"})
                }
        }
}

func main() {
        r := gin.Default()
        r.Use(check())

        r.GET("/test", func(c *gin.Context) {
                c.JSON(200, gin.H{"message": "path ok"})
        })

        r.Run()
}
// curl 127.0.0.1:8080/test/haha
// {"message":"path fail"}
// curl  127.0.0.1:8080/test
// {"message":"path ok"}
sleagon commented 5 years ago

You could try https://github.com/sleagon/ginfmt to handle your error/succ response easily~