-1

When I insert a record to the database it is saving, but my problem is that in Golang I am not able to handle errors. Suppose right now I am getting the error like Duplicate keys in my console but rather I want to handle it in JSON response, how would I handle this error?

Here is my code:

func main() {
    router := gin.New()
    router.Use(gin.Logger())
    router.Use(gin.Recovery())
    db, err := sql.Open("mysql", "root:password@tcp(gpstest.cksiqniek8yk.ap-south-1.rds.amazonaws.com:3306)/tech")
    if err != nil {
        fmt.Print(err.Error())
    }
    // make sure connection is available
    err = db.Ping()
    if err != nil {
        fmt.Print(err.Error())
    }
    router.POST("/validate", func(c *gin.Context) {
        var (
            cat  Cat
            cats []Cat
        )
        c.BindJSON(&cat)

        rows, err := db.Query("select a.id, r.id from admin_user as a inner join roles as r on r.id = a.id where r.name = '" + cat.roleName + "' AND a.admin_email = '" + cat.adminEmail + "' AND a.id = ' + cat.ID + ' AND r.id = ' + cat.ID1 + ' ;")
        if err != nil {
            log.Fatal(err)
        }

        if rows.Next() {
            err = rows.Scan(&cat.ID, &cat.ID1)
            cats = append(cats, cat)
            if err != nil {
                fmt.Print(err.Error())
            }
            c.JSON(http.StatusOK, gin.H{
                "result": cats,
                "count":  len(cats),
            })
        } else {
            var buffer bytes.Buffer

            stmt, err := db.Prepare("INSERT INTO admin_roles(admin_id, role_id) values(?,?)")
            if err != nil {
                panic(err)
            }
            _, err = stmt.Exec(cat.ID, cat.ID1)

            if err != nil {
                fmt.Print(err.Error())
            }
            buffer.WriteString("cat.ID")
            buffer.WriteString(" ")
            buffer.WriteString("cat.ID1")
            defer stmt.Close()
            name1 := buffer.String()
            c.JSON(http.StatusOK, gin.H{
                "message": fmt.Sprintf(" %s successfully created", name1),
            })
        }

    })
    router.Run(":4500")
    //return router
}

And here is the error which I am getting in console.

Error 1062: Duplicate entry '2-2' for key 'admin_id_role_id_uk_idx'[GIN]. I want to handle this error in JSON format.

David Buck
  • 3,752
  • 35
  • 31
  • 35
waseem khan
  • 65
  • 1
  • 3
  • 8

1 Answers1

0

You can set UNIQUE option for the interested column. And to show the error in JSON response to HTTP request, just declare and initialize a variable before the handling part and alter its result according to the response from DB query.

Even though I would firstly prefer to query against DB whether the input data has already been saved in DB.

Berkant İpek
  • 1,077
  • 12
  • 20
  • Thank you so much I figured it out how to do this! – waseem khan Apr 11 '18 at 04:17
  • And also, do not forget to fail in the case of sql.Open call's err is present. Otherwise the rest of the calls to DB will all fail. It is not appropriate to continue the execution without an established DB connection. You should have failed there the exit the program with Fatal. – Berkant İpek Apr 11 '18 at 05:35
  • I got it Berkant Thank you and will take about db connectivities. – waseem khan Apr 11 '18 at 09:48