-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
51 lines (45 loc) · 1.5 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
package middleware
import (
"context"
"github.com/ixtendio/gofre/errors"
"github.com/ixtendio/gofre/handler"
"github.com/ixtendio/gofre/router/path"
"github.com/ixtendio/gofre/response"
"net/http"
)
type ResponseSupplier func(statusCode int, err error) response.HttpResponse
// Error2HttpStatusCode translates an error to an HTTP status code
var Error2HttpStatusCode = func(err error) int {
if _, ok := err.(errors.ErrBadRequest); ok {
return http.StatusBadRequest
} else if _, ok := err.(errors.ErrObjectNotFound); ok {
return http.StatusNotFound
} else if err == errors.ErrUnauthorizedRequest {
return http.StatusUnauthorized
} else if err == errors.ErrWrongCredentials ||
err == errors.ErrAccessDenied {
return http.StatusForbidden
}
return http.StatusInternalServerError
}
// ErrJsonResponse translates an error to a JSON response
func ErrJsonResponse() Middleware {
return ErrResponse(func(statusCode int, err error) response.HttpResponse {
return response.JsonHttpResponse(statusCode, map[string]string{
"error": err.Error(),
})
})
}
// ErrResponse translates an error to an response.HttpResponse
func ErrResponse(responseSupplier ResponseSupplier) Middleware {
return func(handler handler.Handler) handler.Handler {
return func(ctx context.Context, mc path.MatchingContext) (response.HttpResponse, error) {
resp, err := handler(ctx, mc)
if err != nil {
statusCode := Error2HttpStatusCode(err)
return responseSupplier(statusCode, err), nil
}
return resp, err
}
}
}