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?
Gorm seem to be extremely slow. The last time takes almost 60s to query. Whereas if I used "database/sql" mysql. QueryRow() its less than 500ms.
Current state of logging in GORM In order to enable logging for all queries, we need to invoke the LogMode method with true as the argument. The logs below are for a simple /GET API call which retrieves records from the orders and items table.
The GORM is fantastic ORM library for Golang, aims to be developer friendly. It is an ORM library for dealing with relational databases. This gorm library is developed on the top of database/sql package. The overview and feature of ORM are: Full-Featured ORM (almost)
UPDATE: for gorm v2
:
Use the Logger
in gorm.Config
:
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
For gorm v1
:
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With