GORM db.First print log automatically

Viewed 538

I am using the latest GORM v2.

When I use db.First(&AoiArea{}), it triggers a record not found error output in the log if nothing is found.

    if err := db.First(&AoiArea{}).Error; errors.Is(err, gorm.ErrRecordNotFound) {
        // Do something
    }

Automatic O/P from First:

2021/09/17 09:02:24 ←[31;1mE:/xyz-api/models/utils.go:47 ←[35;1mrecord not found ←[0m←[33m[0.000ms] ←[34;1m[rows:0]←[0m SELECT * FROM "aoi_area" ORDER BY "aoi_area"."id" LIMIT 1

Is there any way to prevent this default log?

I see there is a similar question here https://gorm.io/docs/error_handling.html#comment-5083714457 in their documentation Q&A but no appropriate answer.

1 Answers

Yes, First will always print the error log.

If you want to avoid the ErrRecordNotFound error, you could use Find like db.Limit(1).Find(&user), the Find method accepts both struct and slice data

doc is here: https://gorm.io/docs/query.html

You can try this

db.Limit(1).Find(&AoiArea{})
Related