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"
|
||||
)
|
||||
|
||||
type ApiError struct {
|
||||
Message string `json:"message"`
|
||||
Err error `json:"error"`
|
||||
Status int
|
||||
}
|
||||
|
||||
func (a *ApiError) Error() string {
|
||||
return a.Message
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
addr string
|
||||
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) {
|
||||
s.mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := handler(w, r); err != nil {
|
||||
s.Error(w, "something bad happened", err, 500)
|
||||
err := handler(w, r)
|
||||
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)
|
||||
}
|
||||
|
||||
func (s *Server) Error(w http.ResponseWriter, msg string, err error, status int) {
|
||||
var e *string
|
||||
if err != nil {
|
||||
e = new(err.Error())
|
||||
}
|
||||
|
||||
s.JSON(w, struct {
|
||||
Message string `json:"message"`
|
||||
Error *string `json:"error"`
|
||||
}{
|
||||
func (s *Server) Error(msg string, err error, status int) error {
|
||||
return &ApiError{
|
||||
Message: msg,
|
||||
Error: e,
|
||||
}, status)
|
||||
Err: err,
|
||||
Status: status,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) ListenAndServe() error {
|
||||
|
||||
Reference in New Issue
Block a user