Files
calculate_negative_points/internal/api/middleware/error.go
Eugene Howe b0957bfa49
Some checks failed
Docker Build and Publish / publish (push) Failing after 1m33s
webapp
2026-02-17 09:47:30 -05:00

65 lines
1.8 KiB
Go

package middleware
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
// "github.com/getsentry/sentry-go"
"clintonambulance.com/calculate_negative_points/internal/utils"
"github.com/swaggest/rest"
"github.com/swaggest/rest/nethttp"
)
func ErrorResponder(w http.ResponseWriter, error string, code int) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(code)
_ = json.NewEncoder(w).Encode(utils.NewApplicationError(error, code))
}
type errorWithFields interface {
error
Fields() map[string]interface{}
}
// ErrorHandler middleware centralizes error handling and translation of errors between different error types
func ErrorHandler(next http.Handler) http.Handler {
var h *nethttp.Handler
if nethttp.HandlerAs(next, &h) {
resp := func(ctx context.Context, err error) (int, interface{}) {
// Handle AWS errors
// Application-specific error handling: if this error has a marker interface, serialize it as JSON
var customErr utils.CustomApplicationError
if errors.As(err, &customErr) {
return customErr.HTTPStatus(), customErr
}
// More detailed validation error messages
var validationErr errorWithFields
if errors.As(err, &validationErr) {
detailedErrorMessages := make([]string, len(validationErr.Fields()))
i := 0
for k, v := range validationErr.Fields() {
detailedErrorMessages[i] = fmt.Sprintf("%s: %v", k, v)
i++
}
return http.StatusUnprocessableEntity, utils.ApplicationError{
Message: fmt.Sprintf("Validation errors: %s", strings.Join(detailedErrorMessages, ", ")),
}
}
code, er := rest.Err(err)
return code, utils.ApplicationError{
Message: er.ErrorText,
}
}
h.MakeErrResp = resp
}
return next
}