gorm: How to check if error type is DUPLICATE KEY
Your Question
I have unique index key and when i try to insert duplicate record i get this error ERROR: duplicate key value violates unique constraint "idx_itemid_partid" (SQLSTATE 23505) but i want to show different message to the frontend based on ERROR TYPE but in gorm i do not see any Duplicate error type please check screenshot. How do i use the validation for duplicate error type
if err != nil && errors.Is(err, gorm.ErrDuplicateKey) { // how do i do this ?
fmt.Println("Duplicate key found.")
}
The document you expected this should be explained
N/A
Expected answer
Should have error type duplicate
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 23
- Comments: 31 (1 by maintainers)
Commits related to this issue
- Make dialect translated errors more visible When error handling, errors like `ErrRecordNotFound` are available only when Dialect Translated Errors are enabled. This section was not obvious when skimm... — committed to berinaniesh/gorm.io by berinaniesh 8 months ago
- Make dialect translated errors more visible When error handling, errors like `ErrRecordNotFound` are available only when Dialect Translated Errors are enabled. This section was not obvious when skimm... — committed to berinaniesh/gorm.io by berinaniesh 8 months ago
- Make dialect translated errors more visible (#721) When error handling, errors like `ErrRecordNotFound` are available only when Dialect Translated Errors are enabled. This section was not obvious w... — committed to go-gorm/gorm.io by berinaniesh 8 months ago
If you want to check type of error, just do it.
I think better would be easier to have such common error in predefined errors emitted by gorm.
use mysql as example, check it like:
Currently i am able to solve this issue with a hack (even i expect
gormshould solve it in a better way)why are this closed?
Try this, it works for me!
first you have to defined gorm error struct, your can find the format by json.Marshal(err)
then, marshal the error to json then unmarshal it back
you can check the error type by newError.Number !
if you got duplicate entry error, format may be like this
Makes sense. FYI, for others that need this for postgres, since gorm uses pgx, you can do the following:
you then can use this to match error codes: https://github.com/jackc/pgerrcode/blob/master/errcode.go
I created a naive function to handle errors from DB (SQLite/PostgreSQL only), and the unique violation handling part is:
Could still use a more universal solution to this than explicitly using psql/mysql error codes.
error is an interface, you can get the mysqlErr by type asseration
@jinzhu How do i do that for postgres it’s not working
Does the TranslateError flag also work when using gorm.Open() with an existing *sql.DB?
TranslateError:true works just fine when instantiating my *gorm.DB with:
But when I try to open a gorm connection with an existing sql connection (specifically during a TestMain() function that includes a dockertest setup), the errors don’t get translated (for example, the Unique Key Violation). Here is how I’m opening it in my TestMain():
It will panic :
@khanakia
Hope it helps:
Sqlite3
+1 for an elegant way to handle this that doesn’t break multi-database support for the official options; i.e. a GORM error var. I’ll submit a PR if I can get work approval.
@jinzhu Any update on this ? I have check everywhere there is no solution i found for this.
Just in case if anyone else face with the same issue - here is what works for me (SQLite):
For Postgres
Use this function to check for errors in SQLite 3
Example after the INSERT request:
@silvioprog you forgot to mention which package you’re using to get the error constants.
https://github.com/jackc/pgerrcode
if you use
postgresqlyou can check the error code whether equals topgerrcode.UniqueViolation. before you check the error code, you should convert error type to*pgconn.PgErrorfirst, it works.pgx error code reference
Also curious about this. Seems like a pretty common error case that developers might want to handle gracefully
any future plan to create predefined error for this case ?