feat(router): error handling of routes

This commit is contained in:
Guz
2024-10-07 15:40:26 -03:00
parent 1c7131c216
commit 47c570855f
3 changed files with 85 additions and 0 deletions

16
router/rerrors/400s.go Normal file
View File

@@ -0,0 +1,16 @@
package rerrors
import "net/http"
func MissingParameters(params []string) RouteError {
return NewRouteError(http.StatusBadRequest, "Missing parameters", map[string]any{
"missing_parameters": params,
})
}
func MethodNowAllowed(method string, allowedMethods []string) RouteError {
return NewRouteError(http.StatusMethodNotAllowed, "Method not allowed", map[string]any{
"method": method,
"allowed_methods": allowedMethods,
})
}

12
router/rerrors/500s.go Normal file
View File

@@ -0,0 +1,12 @@
package rerrors
import (
"errors"
"net/http"
)
func InternalError(errs ...error) RouteError {
return NewRouteError(http.StatusInternalServerError, "Internal server error", map[string]any{
"errors": errors.Join(errs...),
})
}

57
router/rerrors/errors.go Normal file
View File

@@ -0,0 +1,57 @@
package rerrors
import (
"encoding/json"
"fmt"
"net/http"
)
type RouteError struct {
StatusCode int `json:"status_code"`
Error string `json:"error"`
Info map[string]any `json:"info"`
}
func NewRouteError(status int, error string, info ...map[string]any) RouteError {
rerr := RouteError{StatusCode: status, Error: error}
if len(info) > 0 {
rerr.Info = info[0]
} else {
rerr.Info = map[string]any{}
}
return rerr
}
func (rerr RouteError) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if rerr.StatusCode == 0 {
rerr.StatusCode = http.StatusNotImplemented
}
if rerr.Error == "" {
rerr.Error = "MISSING ERROR DESCRIPTION"
}
if rerr.Info == nil {
rerr.Info = map[string]any{}
}
w.Header().Set("Content-Type", "application/json")
j, err := json.Marshal(rerr)
if err != nil {
j, _ := json.Marshal(RouteError{
StatusCode: http.StatusInternalServerError,
Error: "Failed to marshal error message to JSON",
Info: map[string]any{
"source_value": fmt.Sprintf("%#v", rerr),
"error": err.Error(),
},
})
w.Write(j)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(j)
w.WriteHeader(rerr.StatusCode)
}