dongzhenqi2015 2019-04-28 16:01
浏览 192
已采纳

如何在Go-Gorm中禁用默认错误记录器

I am using GORM with MySQL, I have encountered and handled the error Error 1062: Duplicate entry. The problem is that it's still printed to the console.

Code in gym/models/auth.go:49:

func AddAuth(username, password string) error {
    passwordHash, err := auth.HashPassword(password, argon2Conf)
    if err != nil {
        return err
    }
    userAuth := Auth{
        Username: username,
        Password: passwordHash,
    }
    return db.Create(&userAuth).Error
}

I am handling the error in the handler function:

func SignUpHandler(c *gin.Context) {
    var form user
    if err := c.ShouldBind(&form); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    if err := models.AddAuth(form.Username, form.Password); err == nil {
        c.JSON(http.StatusOK, gin.H{"status": "you are signed in"})
    } else {
        // I think I have handled the sql error here
        c.JSON(http.StatusBadRequest, gin.H{"error": "sign in failed"})
    }
}

When I send a POST request, the error is correctly handled and I get the correct response with {"error": "sign in failed"}. But the console still prints this error message:

(/...../gym/models/auth.go:49) 
[2019-04-28 23:37:06]  Error 1062: Duplicate entry '123123' for key 'username' 
[GIN] 2019/04/28 - 23:37:06 | 400 |  136.690908ms |             ::1 | POST     /signup

I am confused since I handled the error but it still gets printed. How to prevent this error from getting printed to the error log? Or am I handle the error correct?

  • 写回答

1条回答 默认 最新

  • dtyqflrr775518 2019-04-28 16:33
    关注

    Use db.LogMode to silence the default error logger.

    LogMode set log mode, true for detailed logs, false for no log, default, will only print error logs.

    db.LogMode(false) should do the job!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献