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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看