This repository has been archived by the owner on Oct 31, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
errors.go
54 lines (48 loc) · 1.75 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
package controller
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/kataras/iris/v12/context"
"github.com/pkg/errors"
"net/http"
)
// wrapPgError will wrap and return an error to the client. But will try to infer a status code from the error it is
// given. If it cannot infer a status code, an InternalServerError is used.
func (c *Controller) wrapPgError(ctx *context.Context, err error, msg string, args ...interface{}) {
switch errors.Cause(err) {
case pg.ErrNoRows:
ctx.SetErr(errors.Errorf("%s: record does not exist", fmt.Sprintf(msg, args...)))
ctx.StatusCode(http.StatusNotFound)
ctx.StopExecution()
default:
switch actualErr := errors.Cause(err).(type) {
case pg.Error:
cleanedErr, status := c.sanitizePgError(actualErr)
c.wrapAndReturnError(ctx, cleanedErr, status, msg, args...)
default:
c.wrapAndReturnError(ctx, err, http.StatusInternalServerError, msg, args...)
}
}
}
func (c *Controller) sanitizePgError(err pg.Error) (error, int) {
switch err.Field(67) {
case "23505": // Duplicate
// TODO Return actual duplicate information in this error.
return errors.New("a similar object already exists"), http.StatusBadRequest
default:
return err, http.StatusInternalServerError
}
}
func (c *Controller) wrapAndReturnError(ctx *context.Context, err error, status int, msg string, args ...interface{}) {
ctx.SetErr(errors.Wrapf(err, msg, args...))
ctx.StatusCode(status)
ctx.StopExecution()
}
func (c *Controller) returnError(ctx *context.Context, status int, msg string, args ...interface{}) {
ctx.SetErr(errors.Errorf(msg, args...))
ctx.StatusCode(status)
ctx.StopExecution()
}
func (c *Controller) badRequest(ctx *context.Context, msg string, args ...interface{}) {
c.returnError(ctx, http.StatusBadRequest, msg, args...)
}