効果的なエラー処理は、特にGORMを使用してデータベースとやりとりする場合において、堅牢なGoアプリケーション開発の礎石です。 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 ( |
方言を翻訳したエラー
GORMは使用されているSQL方言に関する特定のエラーを返すことができます。TranslateError
が有効な場合、GORMはデータベース固有のエラーを独自に一般化したエラーに変換します。
db, err := gorm.Open(postgres.Open(postgresDSN), &gorm.Config{TranslateError: true}) |
- ErrDuplicatedKey
このエラーは、レコード挿入操作がUNIQUE制約に違反した場合に発生します。
result := db.Create(&newRecord) |
- ErrForeignKeyViolated
このエラーは外部キー制約に違反している場合に発生します。
result := db.Create(&newRecord) |
TranslateError
を有効にすることで、GORMはデータベース固有のエラーを一般的なGORMエラータイプに翻訳し、異なるデータベース間でより統一されたエラー処理方法を提供します。
エラーの一覧
GORMが返すエラーの一覧については、GORMのドキュメントの エラーリスト を参照してください。