在Go语言的应用开发中,特别是在使用GORM与数据库交互时,有效的错误处理是构建稳健应用的基石。 GORM’s approach to error handling requires a nuanced understanding based on the API style you’re using.
基本错误处理
Generics API
With the Generics API, errors are returned directly from the operation methods, following Go’s standard error handling pattern:
ctx := context.Background() |
Traditional API
With the Traditional API, GORM integrates error handling into its chainable method syntax. *gorm.DB
实例包含一个Error
字段,当发生错误时会被设置。 通常的做法是在执行数据库操作后,特别是在完成方法(Finisher Methods)后,检查这个字段。
在一系列方法之后,检查Error
字段是至关重要的:
if err := db.Where("name = ?", "jinzhu").First(&user).Error; err != nil { |
或者
if result := db.Where("name = ?", "jinzhu").First(&user); result.Error != nil { |
ErrRecordNotFound
当使用First
、Last
、Take
等方法未找到记录时,GORM会返回ErrRecordNotFound
。
Generics API
ctx := context.Background() |
Traditional API
err := db.First(&user, 100).Error |
处理错误代码
许多数据库返回带有特定代码的错误,这些代码可能表明各种问题,如约束违规、连接问题或语法错误。 Handling these error codes in GORM requires parsing the error returned by the database and extracting the relevant code.
import ( |
方言转换错误
当启用TranslateError
时,GORM可以返回与所使用的数据库方言相关的特定错误,GORM将数据库特有的错误转换为其自己的通用错误。
db, err := gorm.Open(postgres.Open(postgresDSN), &gorm.Config{TranslateError: true}) |
- ErrDuplicatedKey
当插入操作违反唯一约束时,会发生此错误:
result := db.Create(&newRecord) |
- ErrForeignKeyViolated
当违反外键约束时,会遇到此错误:
result := db.Create(&newRecord) |
通过启用TranslateError
,GORM提供了一种更统一的错误处理方式,将不同数据库的特定错误转换为常见的GORM错误类型。
Errors
要获取GORM可能返回的完整错误列表,请参考GORM文档中的错误列表。