-
-
Notifications
You must be signed in to change notification settings - Fork 109
/
error.go
48 lines (41 loc) · 1.06 KB
/
error.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
package sqlcon
import (
"database/sql"
"net/http"
"github.com/go-sql-driver/mysql"
"github.com/lib/pq"
"github.com/ory/herodot"
"github.com/pkg/errors"
)
var (
ErrUniqueViolation = &herodot.DefaultError{
CodeField: http.StatusConflict,
StatusField: http.StatusText(http.StatusConflict),
ErrorField: "Unable to insert or update resource because a resource with that value exists already",
}
ErrNoRows = &herodot.DefaultError{
CodeField: http.StatusNotFound,
StatusField: http.StatusText(http.StatusNotFound),
ErrorField: "Unable to locate the resource",
}
)
func HandleError(err error) error {
if err == sql.ErrNoRows {
return errors.WithStack(ErrNoRows)
}
if err, ok := err.(*pq.Error); ok {
switch err.Code.Name() {
case "unique_violation":
return errors.Wrap(ErrUniqueViolation, err.Error())
}
return errors.WithStack(err)
}
if err, ok := err.(*mysql.MySQLError); ok {
switch err.Number {
case 1062:
return errors.Wrap(ErrUniqueViolation, err.Error())
}
return errors.WithStack(err)
}
return errors.WithStack(err)
}