title: How to handle the errors in Golang for inserting a duplicate keys?
body: <p>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?</p>
  <p>Here is my code:</p>
  <pre><code>func main() {
      router := gin.New()
      router.Use(gin.Logger())
      router.Use(gin.Recovery())
      db, err := sql.Open(&quot;mysql&quot;, &quot;root:password@tcp(gpstest.cksiqniek8yk.ap-south-1.rds.amazonaws.com:3306)/tech&quot;)
      if err != nil {
          fmt.Print(err.Error())
      }
      // make sure connection is available
      err = db.Ping()
      if err != nil {
          fmt.Print(err.Error())
      }
      router.POST(&quot;/validate&quot;, func(c *gin.Context) {
          var (
              cat  Cat
              cats []Cat
          )
          c.BindJSON(&amp;cat)
  
          rows, err := db.Query(&quot;select a.id, r.id from admin_user as a inner join roles as r on r.id = a.id where r.name = '&quot; + cat.roleName + &quot;' AND a.admin_email = '&quot; + cat.adminEmail + &quot;' AND a.id = ' + cat.ID + ' AND r.id = ' + cat.ID1 + ' ;&quot;)
          if err != nil {
              log.Fatal(err)
          }
  
          if rows.Next() {
              err = rows.Scan(&amp;cat.ID, &amp;cat.ID1)
              cats = append(cats, cat)
              if err != nil {
                  fmt.Print(err.Error())
              }
              c.JSON(http.StatusOK, gin.H{
                  &quot;result&quot;: cats,
                  &quot;count&quot;:  len(cats),
              })
          } else {
              var buffer bytes.Buffer
  
              stmt, err := db.Prepare(&quot;INSERT INTO admin_roles(admin_id, role_id) values(?,?)&quot;)
              if err != nil {
                  panic(err)
              }
              _, err = stmt.Exec(cat.ID, cat.ID1)
  
              if err != nil {
                  fmt.Print(err.Error())
              }
              buffer.WriteString(&quot;cat.ID&quot;)
              buffer.WriteString(&quot; &quot;)
              buffer.WriteString(&quot;cat.ID1&quot;)
              defer stmt.Close()
              name1 := buffer.String()
              c.JSON(http.StatusOK, gin.H{
                  &quot;message&quot;: fmt.Sprintf(&quot; %s successfully created&quot;, name1),
              })
          }
  
      })
      router.Run(&quot;:4500&quot;)
      //return router
  }
  </code></pre>
  <p>And here is the error which I am getting in console.</p>
  <blockquote>
  <p>Error 1062: Duplicate entry '2-2' for key 'admin_id_role_id_uk_idx'[GIN].
  I want to handle this error in JSON format.</p>
  </blockquote>