kleinTodo/server/handler/errorHandlers.go

63 lines
1.5 KiB
Go
Raw Permalink Normal View History

2025-07-26 23:31:00 +02:00
package handler
import (
2025-07-26 23:57:44 +02:00
"log/slog"
2025-07-26 23:31:00 +02:00
"net/http"
)
func InternalServerErrorHandler(w http.ResponseWriter, err error) {
setError(w, http.StatusInternalServerError, err.Error())
}
func NotFoundHandler(w http.ResponseWriter) {
setError(w, http.StatusNotFound, "404 Not Found")
}
func BadRequestHandler(w http.ResponseWriter) {
setError(w, http.StatusBadRequest, "404 Not Found")
}
func UnprocessableEntityHandler(w http.ResponseWriter, err error) {
setError(w, http.StatusUnprocessableEntity, err.Error())
}
func UnauthorizedHandler(w http.ResponseWriter) {
setError(w, http.StatusUnauthorized, "Unauthorized")
}
func NotImplementedHandler(w http.ResponseWriter) {
setError(w, http.StatusNotImplemented, "WORK IN PROGRESS")
}
func setError(w http.ResponseWriter, httpStatus int, errorMessage string) {
w.WriteHeader(httpStatus)
if _, err := w.Write([]byte(errorMessage)); err != nil {
2025-08-23 13:28:48 +02:00
slog.Error(err.Error())
2025-07-26 23:31:00 +02:00
}
return
}
func handleError(w http.ResponseWriter, status int, err error) bool {
if err != nil {
switch status {
case http.StatusInternalServerError:
InternalServerErrorHandler(w, err)
case http.StatusNotFound:
NotFoundHandler(w)
case http.StatusBadRequest:
BadRequestHandler(w)
case http.StatusUnauthorized:
UnauthorizedHandler(w)
case http.StatusNotImplemented:
NotImplementedHandler(w)
case http.StatusUnprocessableEntity:
UnprocessableEntityHandler(w, err)
default:
InternalServerErrorHandler(w, err)
}
2025-07-26 23:57:44 +02:00
slog.Error(err.Error())
2025-07-26 23:31:00 +02:00
return true
}
return false
}