找不到实体时正确的错误处理

I'm writing a Go application which has a database package. Now in database package there are a couple of methods which you can call for getting an entity based on some fields.

I was wondering what is the best practice for error handling in Go when no entity is found. Should I return errors in my own database package or return nil as the value?

I know google's datastore returns error when no entity is found.

Right now I'm using gorm and it also returns error when no entity is found.

I'm wondering you can simply return nil as the value instead of returning an error. Am I missing a point?

If you are using gorm, there is a function specifically for that; namely,

// IsRecordNotFoundError returns true if error contains a RecordNotFound error
func IsRecordNotFoundError(err error) bool {}

You can use it as following:

err = db.Find(object).Error
if err != nil {
    if gorm.IsRecordNotFoundError(err) {
        // handle object not found
    } else {
        return err
    }
}

and for your question:

I'm wondering you can simply return nil as the value instead of returning an error

It really depends on your design; so if you want to separate your database layer, then you should still inform the user about this error using your own exported error type and let them handle it as they wish.

you can use this code:

  user:=&User{}
  if db.First(&user, "username=?", mobile).RecordNotFound() {
     return nil
  }
  return user