Gin: how to handle error in router handlerFunc?

Created on 15 Jun 2019  路  4Comments  路  Source: gin-gonic/gin

Usually

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

    r.GET("/id", func(c *gin.Context) {

        var people People

        err := c.ShouldBindJSON(&people)

        if err != nil {
            // handle err
        }

        // do something with sql
        // handle err(empty error, sql error etc)

        if err != nil {
            // handle err
        }
        if err != nil {
            // handle err
        }

    })
}

the way to handle error

c.JSON(error code, gin.H{
    "msg": "some error msg",
    "code": "code",
})
return

this way can't reuse, I try Abort func to handle but failed, and a bad solution is to use panic and recovery, like this

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

    gin.re

    r.GET("/id", func(c *gin.Context) {

        var people People

        err := c.ShouldBindJSON(&people)

        c.Abort()

        CheckError(err)

        // do something with sql
        // handle err(empty error, sql error etc)
        CheckError(err)
        CheckError(err)

    })
}

func CheckError(err error)  {
    if err != nil {
        panic(err)
    }
}

Most helpful comment

I mean you're trying to deal with specific error, right?
I wrote a middleware to handle error:

func ErrorHandle() gin.HandlerFunc {
    return func (c *gin.Context) {
        c.Next()
        err := c.Errors.Last()
        if err == nil {
            return
        }

        // Use reflect.TypeOf(err.Err) to known the type of your error
        if error, ok := errors.Cause(err.Err).(*myspace.KindOfClientError); ok {
            c.JSON(400, gin.H{
                "error": "Blah blahhh"
            })
            return 
        }
    }
}

All 4 comments

I mean you're trying to deal with specific error, right?
I wrote a middleware to handle error:

func ErrorHandle() gin.HandlerFunc {
    return func (c *gin.Context) {
        c.Next()
        err := c.Errors.Last()
        if err == nil {
            return
        }

        // Use reflect.TypeOf(err.Err) to known the type of your error
        if error, ok := errors.Cause(err.Err).(*myspace.KindOfClientError); ok {
            c.JSON(400, gin.H{
                "error": "Blah blahhh"
            })
            return 
        }
    }
}

@vuongggggg no, I want to handle error and code should be stopped

c.AbortWithStatusJSON(400, gin.H{
  "error": "Blah blahhh"
})

// continue
c.JSON(200, gin.H{
  "msg": "ok"
})

The error handling should be the syntactic sugar that golang wants to add.
You can look at https://github.com/golang/go/issues/32676

@guonaihong oh, thank you

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lilee picture lilee  路  3Comments

ghost picture ghost  路  3Comments

boneq picture boneq  路  3Comments

nxvl picture nxvl  路  3Comments

mastrolinux picture mastrolinux  路  3Comments