router handler to report errors via json
Signed-off-by: Michael <michael.lindman@gmail.com>
This commit is contained in:
parent
15e52bd393
commit
adf8750c31
8
go.mod
8
go.mod
|
@ -5,8 +5,8 @@ go 1.15
|
|||
require (
|
||||
github.com/gorilla/csrf v1.7.0
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/magefile/mage v1.11.0 // indirect
|
||||
github.com/sirupsen/logrus v1.8.0
|
||||
golang.org/x/sys v0.0.0-20210308170721-88b6017d0656 // indirect
|
||||
google.golang.org/protobuf v1.25.0
|
||||
github.com/sirupsen/logrus v1.8.1
|
||||
golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4 // indirect
|
||||
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 // indirect
|
||||
google.golang.org/protobuf v1.26.0
|
||||
)
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package router
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
|
@ -14,6 +15,7 @@ type HTTPStatusError struct {
|
|||
statuscode int
|
||||
err error
|
||||
body interface{}
|
||||
output bool
|
||||
}
|
||||
|
||||
// HTTPError handle HTTP error
|
||||
|
@ -26,6 +28,11 @@ func HTTPErrorWithBody(body interface{}, statuscode int, err error) *HTTPStatusE
|
|||
return &HTTPStatusError{body: body, statuscode: statuscode, err: err}
|
||||
}
|
||||
|
||||
// HTTPErrorWithReport handle HTTP error returning status report
|
||||
func HTTPErrorWithReport(statuscode int, err error) *HTTPStatusError {
|
||||
return &HTTPStatusError{statuscode: statuscode, err: err, output: true}
|
||||
}
|
||||
|
||||
// RespondError HTTP error response
|
||||
func (e *HTTPStatusError) RespondError(w http.ResponseWriter, r *http.Request, re *Router) bool {
|
||||
if e.err != nil {
|
||||
|
@ -35,7 +42,15 @@ func (e *HTTPStatusError) RespondError(w http.ResponseWriter, r *http.Request, r
|
|||
re.logger.Error.Error(e.err)
|
||||
}
|
||||
}
|
||||
if e.body == nil {
|
||||
if e.output {
|
||||
re.Respond(struct {
|
||||
Status string
|
||||
Error string
|
||||
}{
|
||||
Status: fmt.Sprintf("%d %s", e.statuscode, http.StatusText(e.statuscode)),
|
||||
Error: e.err.Error(),
|
||||
}, e.statuscode).ServeHTTP(w, r)
|
||||
} else if e.body == nil {
|
||||
re.handleError(e.statuscode).ServeHTTP(w, r)
|
||||
} else {
|
||||
re.Respond(e.body, e.statuscode).ServeHTTP(w, r)
|
||||
|
|
|
@ -75,8 +75,8 @@ func (re *Router) Response(resp *Response, statuscode int) HandlerFunc {
|
|||
func (re *Router) Respond(data interface{}, status int) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
re.logger.AccessMessage(r, status)
|
||||
w.WriteHeader(status)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if data != nil {
|
||||
if err := json.NewEncoder(w).Encode(data); err != nil {
|
||||
re.logger.Error.Errorf("faield to encode a response: %v", err)
|
||||
|
|
Reference in New Issue