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.