make Server.Error() method to return error instead of sending http response
This commit is contained in:
46
server.go
46
server.go
@@ -5,6 +5,16 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type ApiError struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
Err error `json:"error"`
|
||||||
|
Status int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ApiError) Error() string {
|
||||||
|
return a.Message
|
||||||
|
}
|
||||||
|
|
||||||
type Server struct {
|
type Server struct {
|
||||||
addr string
|
addr string
|
||||||
mux *http.ServeMux
|
mux *http.ServeMux
|
||||||
@@ -19,8 +29,23 @@ func NewServer(addr string) *Server {
|
|||||||
|
|
||||||
func (s *Server) Handle(pattern string, handler func(w http.ResponseWriter, r *http.Request) error) {
|
func (s *Server) Handle(pattern string, handler func(w http.ResponseWriter, r *http.Request) error) {
|
||||||
s.mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
|
s.mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
|
||||||
if err := handler(w, r); err != nil {
|
err := handler(w, r)
|
||||||
s.Error(w, "something bad happened", err, 500)
|
if err != nil {
|
||||||
|
if e, ok := err.(*ApiError); ok {
|
||||||
|
var nestedErr *string
|
||||||
|
if e.Err != nil {
|
||||||
|
nestedErr = new(e.Err.Error())
|
||||||
|
}
|
||||||
|
s.JSON(w, map[string]any{
|
||||||
|
"message": e.Message,
|
||||||
|
"error": nestedErr,
|
||||||
|
}, e.Status)
|
||||||
|
} else {
|
||||||
|
s.JSON(w, map[string]any{
|
||||||
|
"message": "something bad happened",
|
||||||
|
"error": err.Error(),
|
||||||
|
}, 500)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -31,19 +56,12 @@ func (s *Server) JSON(w http.ResponseWriter, data any, status int) error {
|
|||||||
return json.NewEncoder(w).Encode(data)
|
return json.NewEncoder(w).Encode(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) Error(w http.ResponseWriter, msg string, err error, status int) {
|
func (s *Server) Error(msg string, err error, status int) error {
|
||||||
var e *string
|
return &ApiError{
|
||||||
if err != nil {
|
|
||||||
e = new(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
s.JSON(w, struct {
|
|
||||||
Message string `json:"message"`
|
|
||||||
Error *string `json:"error"`
|
|
||||||
}{
|
|
||||||
Message: msg,
|
Message: msg,
|
||||||
Error: e,
|
Err: err,
|
||||||
}, status)
|
Status: status,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) ListenAndServe() error {
|
func (s *Server) ListenAndServe() error {
|
||||||
|
|||||||
Reference in New Issue
Block a user