@@ -3,7 +3,6 @@ package common
3
3
// got error handling idea from https://medium.com/ki-labs-engineering/rest-api-error-handling-in-go-behavioral-type-assertion-509d93636afd
4
4
5
5
import (
6
- "fmt"
7
6
"github.com/asaskevich/govalidator"
8
7
"github.com/labstack/echo/v4"
9
8
"net/http"
@@ -35,14 +34,13 @@ func NewError() *Error {
35
34
type RequestError struct {
36
35
Cause error
37
36
Detail string
38
- Type string
39
37
Status int
40
38
}
41
39
42
40
// NewBindingError creates an error with given data. "bindingType" is the type that is being bound
43
41
// provide short description for "detail" to display to user as error message
44
- func NewBindingError (detail , bindingType string , err error , statusCode int ) * RequestError {
45
- return & RequestError {err , detail , bindingType , statusCode }
42
+ func NewRequestError (detail string , err error , statusCode int ) * RequestError {
43
+ return & RequestError {err , detail , statusCode }
46
44
}
47
45
func (se * RequestError ) Error () string {
48
46
if se .Cause == nil {
@@ -52,8 +50,7 @@ func (se *RequestError) Error() string {
52
50
}
53
51
func (se * RequestError ) ErrorBody () Error {
54
52
body := NewError ()
55
- body .Body ["type" ] = fmt .Sprintf ("Error parsing request of type %s" , se .Type )
56
- body .Body ["detail" ] = se .Detail
53
+ body .Body ["body" ] = se .Detail
57
54
return * body
58
55
}
59
56
@@ -88,16 +85,26 @@ func (e *ValidationError) ErrorBody() Error {
88
85
// CustomHTTPErrorHandler, here we define what to do with each types of errors
89
86
func CustomHTTPErrorHandler (err error , c echo.Context ) {
90
87
code := http .StatusInternalServerError
91
- cErr := err .(ClientError )
92
- switch e := cErr .(type ) {
93
- case * RequestError :
94
- code = e .Status
95
- case * ValidationError :
96
- code = http .StatusBadRequest
97
- }
98
- e := c .JSON (code , cErr .ErrorBody ())
99
- if e != nil {
100
- c .Logger ().Error (e )
88
+ switch err .(type ) {
89
+ case ClientError :
90
+ ce := err .(ClientError )
91
+ e := c .JSON (code , ce .ErrorBody ())
92
+ if e != nil {
93
+ c .Logger ().Error (e )
94
+ }
95
+
96
+ c .Logger ().Error (ce )
97
+ switch e := ce .(type ) {
98
+ case * RequestError :
99
+ code = e .Status
100
+ case * ValidationError :
101
+ code = http .StatusBadRequest
102
+ }
103
+ case * echo.HTTPError :
104
+ e := c .JSON (err .(* echo.HTTPError ).Code , err .(* echo.HTTPError ).Message )
105
+ if e != nil {
106
+ c .Logger ().Error (e )
107
+ }
108
+ c .Logger ().Error (err )
101
109
}
102
- c .Logger ().Error (cErr )
103
110
}
0 commit comments