Define some error codes

This commit is contained in:
Jinzhu 2013-11-15 18:36:39 +08:00
parent 5a02c2ec27
commit 52fd87c57b
5 changed files with 17 additions and 9 deletions

View File

@ -687,6 +687,9 @@ query := db.First(&user).Limit(10).Find(&users)
if err := db.Where("name = ?", "jinzhu").First(&user).Error; err != nil { 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 ## Advanced Usage With Query Chain

View File

@ -2,7 +2,7 @@ package gorm
import ( import (
"errors" "errors"
"fmt"
"regexp" "regexp"
) )
@ -300,7 +300,7 @@ func (s *Chain) RemoveIndex(column string) *Chain {
func (s *Chain) validSql(str string) (result bool) { func (s *Chain) validSql(str string) (result bool) {
result = regexp.MustCompile("^\\s*[\\w\\s,.*()]*\\s*$").MatchString(str) result = regexp.MustCompile("^\\s*[\\w\\s,.*()]*\\s*$").MatchString(str)
if !result { if !result {
s.err(errors.New(fmt.Sprintf("SQL is not valid, %s", str))) s.err(InvalidSql)
} }
return return
} }

2
do.go
View File

@ -395,7 +395,7 @@ func (s *Do) query() {
} }
if !has_record && !is_slice { if !has_record && !is_slice {
s.err(errors.New("Record not found!")) s.err(RecordNotFound)
} }
} }
} }

8
errors.go Normal file
View File

@ -0,0 +1,8 @@
package gorm
import "errors"
var (
RecordNotFound = errors.New("Record Not Found")
InvalidSql = errors.New("Invalid SQL")
)

View File

@ -191,18 +191,15 @@ func TestSaveAndUpdate(t *testing.T) {
user.Name = new_name user.Name = new_name
db.Save(&user) db.Save(&user)
orm := db.Where("name = ?", name).First(&User{}) if db.Where("name = ?", name).First(&User{}).Error != RecordNotFound {
if orm.Error == nil {
t.Errorf("Should raise error when looking for a existing user with an outdated name") t.Errorf("Should raise error when looking for a existing user with an outdated name")
} }
orm = db.Where("name = ?", new_name).First(&User{}) if db.Where("name = ?", new_name).First(&User{}).Error != nil {
if orm.Error != nil {
t.Errorf("Shouldn't raise error when looking for a existing user with the new name") t.Errorf("Shouldn't raise error when looking for a existing user with the new name")
} }
orm = db.Where("name = ?", name2).First(&User{}) if db.Where("name = ?", name2).First(&User{}).Error != nil {
if orm.Error != nil {
t.Errorf("Shouldn't update other users") t.Errorf("Shouldn't update other users")
} }
} }