-
-
Notifications
You must be signed in to change notification settings - Fork 183
/
error_translator.go
40 lines (33 loc) · 1023 Bytes
/
error_translator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package sqlite
import (
"encoding/json"
"gorm.io/gorm"
)
// 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.
var errCodes = map[int]error{
1555: gorm.ErrDuplicatedKey,
2067: gorm.ErrDuplicatedKey,
787: gorm.ErrForeignKeyViolated,
}
type ErrMessage struct {
Code int `json:"Code"`
ExtendedCode int `json:"ExtendedCode"`
SystemErrno int `json:"SystemErrno"`
}
// Translate it will translate the error to native gorm errors.
// We are not using go-sqlite3 error type intentionally here because it will need the CGO_ENABLED=1 and cross-C-compiler.
func (dialector Dialector) Translate(err error) error {
parsedErr, marshalErr := json.Marshal(err)
if marshalErr != nil {
return err
}
var errMsg ErrMessage
unmarshalErr := json.Unmarshal(parsedErr, &errMsg)
if unmarshalErr != nil {
return err
}
if translatedErr, found := errCodes[errMsg.ExtendedCode]; found {
return translatedErr
}
return err
}