diff --git a/README.md b/README.md index f6875f59..d87b5715 100644 --- a/README.md +++ b/README.md @@ -687,6 +687,9 @@ query := db.First(&user).Limit(10).Find(&users) if err := db.Where("name = ?", "jinzhu").First(&user).Error; err != nil { // ... } + +// If no record found, gorm will return RecordNotFound error, you could check it with +db.Where("name = ?", "hello world").First(&User{}).Error == gorm.RecordNotFound ``` ## Advanced Usage With Query Chain diff --git a/chain.go b/chain.go index 1ecef1bc..1f21de39 100644 --- a/chain.go +++ b/chain.go @@ -2,7 +2,7 @@ package gorm import ( "errors" - "fmt" + "regexp" ) @@ -300,7 +300,7 @@ func (s *Chain) RemoveIndex(column string) *Chain { func (s *Chain) validSql(str string) (result bool) { result = regexp.MustCompile("^\\s*[\\w\\s,.*()]*\\s*$").MatchString(str) if !result { - s.err(errors.New(fmt.Sprintf("SQL is not valid, %s", str))) + s.err(InvalidSql) } return } diff --git a/do.go b/do.go index 8b1f902e..b2507ce9 100644 --- a/do.go +++ b/do.go @@ -395,7 +395,7 @@ func (s *Do) query() { } if !has_record && !is_slice { - s.err(errors.New("Record not found!")) + s.err(RecordNotFound) } } } diff --git a/errors.go b/errors.go new file mode 100644 index 00000000..2c968dbf --- /dev/null +++ b/errors.go @@ -0,0 +1,8 @@ +package gorm + +import "errors" + +var ( + RecordNotFound = errors.New("Record Not Found") + InvalidSql = errors.New("Invalid SQL") +) diff --git a/gorm_test.go b/gorm_test.go index 20e2a7d5..a5807af8 100644 --- a/gorm_test.go +++ b/gorm_test.go @@ -191,18 +191,15 @@ func TestSaveAndUpdate(t *testing.T) { user.Name = new_name db.Save(&user) - orm := db.Where("name = ?", name).First(&User{}) - if orm.Error == nil { + if db.Where("name = ?", name).First(&User{}).Error != RecordNotFound { t.Errorf("Should raise error when looking for a existing user with an outdated name") } - orm = db.Where("name = ?", new_name).First(&User{}) - if orm.Error != nil { + if db.Where("name = ?", new_name).First(&User{}).Error != nil { t.Errorf("Shouldn't raise error when looking for a existing user with the new name") } - orm = db.Where("name = ?", name2).First(&User{}) - if orm.Error != nil { + if db.Where("name = ?", name2).First(&User{}).Error != nil { t.Errorf("Shouldn't update other users") } }