Golang sqlx.Get: Checking for no rows returned
1 min readDec 22, 2020
When working with “github.com/jmoiron/sqlx” to fetch rows from the database, the Get
function returns an error if there is an error with your query, or if no rows are returned.
Instead of reading the documentation, I had been testing for this with:
err = db.Get(&user, GET_USER_BY_ID, userId)if err.Error() != "sql: no rows in result set" {
return err
}... handle missing user ...
I had never spent the time to figure out where the message was coming from, but today I finally got around to looking for the right way to do this, and found a helpful comment:
err = db.Get(&user, GET_USER_BY_ID, userId)if err != sql.ErrNoRows {
return err
}... handle missing user ...
Using this strategy, you protect yourself from any change to the text of the error, and save quite a bit of noise in your code. Hope this helps!