error_translator.go 1023 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package sqlite
  2. import (
  3. "encoding/json"
  4. "gorm.io/gorm"
  5. )
  6. // The error codes to map sqlite errors to gorm errors, here is a reference about error codes for sqlite https://www.sqlite.org/rescode.html.
  7. var errCodes = map[int]error{
  8. 1555: gorm.ErrDuplicatedKey,
  9. 2067: gorm.ErrDuplicatedKey,
  10. 787: gorm.ErrForeignKeyViolated,
  11. }
  12. type ErrMessage struct {
  13. Code int `json:"Code"`
  14. ExtendedCode int `json:"ExtendedCode"`
  15. SystemErrno int `json:"SystemErrno"`
  16. }
  17. // Translate it will translate the error to native gorm errors.
  18. // We are not using go-sqlite3 error type intentionally here because it will need the CGO_ENABLED=1 and cross-C-compiler.
  19. func (dialector Dialector) Translate(err error) error {
  20. parsedErr, marshalErr := json.Marshal(err)
  21. if marshalErr != nil {
  22. return err
  23. }
  24. var errMsg ErrMessage
  25. unmarshalErr := json.Unmarshal(parsedErr, &errMsg)
  26. if unmarshalErr != nil {
  27. return err
  28. }
  29. if translatedErr, found := errCodes[errMsg.ExtendedCode]; found {
  30. return translatedErr
  31. }
  32. return err
  33. }