Skip to content

Commit

Permalink
Define some error codes
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Nov 15, 2013
1 parent 5a02c2e commit 52fd87c
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 9 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package gorm

import (
"errors"
"fmt"

"regexp"
)

Expand Down Expand Up @@ -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
}
2 changes: 1 addition & 1 deletion do.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ func (s *Do) query() {
}

if !has_record && !is_slice {
s.err(errors.New("Record not found!"))
s.err(RecordNotFound)
}
}
}
Expand Down
8 changes: 8 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package gorm

import "errors"

var (
RecordNotFound = errors.New("Record Not Found")
InvalidSql = errors.New("Invalid SQL")
)
9 changes: 3 additions & 6 deletions gorm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
Expand Down

0 comments on commit 52fd87c

Please sign in to comment.