How can I differentiate between different types of database errors encountered in GORM (e.g., not found, unique constraint violations)?

Responsive Ad Header

Question

Grade: Education Subject: Support
How can I differentiate between different types of database errors encountered in GORM (e.g., not found, unique constraint violations)?
Asked by:
135 Viewed 135 Answers

Answer (135)

Best Answer
(381)
GORM wraps database errors, but you can still access the underlying error. Use `errors.Is` from the `errors` package to check for specific error types defined by the database driver (e.g., `gorm.ErrRecordNotFound`). Also, examine the error message string, as some drivers provide specific error messages related to constraint violations, which can be parsed to determine the cause.