Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to custom http error handling #1906

Open
zxysilent opened this issue May 20, 2019 · 2 comments
Open

How to custom http error handling #1906

zxysilent opened this issue May 20, 2019 · 2 comments

Comments

@zxysilent
Copy link

  • With issues:

    • Use the search tool before opening a new issue.
    • Please provide source code and commit sha if you found a bug.
    • Review existing issues and provide feedback or react to them.
  • go version:
    go version go1.12.5 windows/amd64

  • gin version (or commit ref):
    v1.4.0

  • operating system:
    windows 10 amd 64

Description

How to custom http error handling

Screenshots

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

@guonaihong
Copy link
Contributor

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
Copy link

sleagon commented Oct 30, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants