Files
Tim Wundenberg 1be46780bb
All checks were successful
Build and Push Docker Image / Build-And-Push-Docker-Image (push) Successful in 1m19s
feat: extract into remaining packages
There has been a cyclic dependency.
transaction
	-> treasure_chest
	-> transaction_recurring
	-> transaction

This has been temporarily solved by moving the GenerateTransactions
function into the transaction package. In the future, this function has
to be rewritten to use a proper Service insteas of direct DB access or
replaced with a different system entirely.
2025-12-31 22:26:59 +01:00

71 lines
1.7 KiB
Go

package core
import (
"context"
"database/sql"
"errors"
"log/slog"
"net/http"
"strings"
)
var (
ErrNotFound = errors.New("the value does not exist")
ErrAlreadyExists = errors.New("row already exists")
ErrInternal = errors.New("internal server error")
ErrUnauthorized = errors.New("you are not authorized to perform this action")
ErrBadRequest = errors.New("bad request")
)
func TransformAndLogDbError(ctx context.Context, module string, r sql.Result, err error) error {
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
slog.ErrorContext(ctx, "database sql", "module", module, "err", err)
return ErrInternal
}
if r != nil {
rows, err := r.RowsAffected()
if err != nil {
slog.ErrorContext(ctx, "database rows affected", "module", module, "err", err)
return ErrInternal
}
if rows == 0 {
slog.InfoContext(ctx, "row not found", "module", module)
return ErrNotFound
}
}
return nil
}
func HandleError(w http.ResponseWriter, r *http.Request, err error) {
switch {
case errors.Is(err, ErrUnauthorized):
TriggerToastWithStatus(r.Context(), w, r, "error", "You are not autorized to perform this operation.", http.StatusUnauthorized)
return
case errors.Is(err, ErrBadRequest):
TriggerToastWithStatus(r.Context(), w, r, "error", extractErrorMessage(err), http.StatusBadRequest)
return
case errors.Is(err, ErrNotFound):
TriggerToastWithStatus(r.Context(), w, r, "error", extractErrorMessage(err), http.StatusNotFound)
return
}
TriggerToastWithStatus(r.Context(), w, r, "error", "Internal Server Error", http.StatusInternalServerError)
}
func extractErrorMessage(err error) string {
errMsg := err.Error()
if errMsg == "" {
return ""
}
return strings.SplitN(errMsg, ":", 2)[0]
}