-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors.go
77 lines (63 loc) · 1.26 KB
/
errors.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package postgres
import (
"context"
"errors"
"net"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
type PgErrorCode int
const (
ErrContextDeadline PgErrorCode = iota
ErrNoRows
ErrUniqViolation
ErrOther
ErrBeginTransaction
ErrCommitTransaction
ErrNoConnection
)
type PgError struct {
code PgErrorCode
msg string
}
func (e PgError) Error() string {
return e.msg
}
func (e PgError) Code() PgErrorCode {
return e.code
}
func NewPgError(code PgErrorCode, err error) *PgError {
return &PgError{code, err.Error()}
}
func ConvertError(err error) *PgError {
if err == nil {
return nil
}
if pgErr, ok := err.(*PgError); ok {
return pgErr
}
if ne, ok := err.(net.Error); ok {
return NewPgError(ErrNoConnection, ne)
}
switch {
case errors.Is(err, context.Canceled), pgconn.Timeout(err):
return NewPgError(ErrContextDeadline, err)
case errors.Is(err, pgx.ErrNoRows):
return NewPgError(ErrNoRows, err)
default:
var pgErr *pgconn.PgError
var code string
if errors.As(err, &pgErr) {
code = pgErr.Code
}
switch code {
case "":
return NewPgError(ErrOther, err)
case pgerrcode.UniqueViolation:
return NewPgError(ErrUniqViolation, err)
default:
return NewPgError(ErrOther, err)
}
}
}