package store import ( "context" "errors" "log/slog" "net" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/common" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" ) func isUniqueViolation(err error) bool { pgErr, ok := errors.AsType[*pgconn.PgError](err) return ok && pgErr.Code == "23505" } // dbError maps driver failures to contract errors. Unexpected failures are // logged with their cause so a 500 is never silent. func dbError(err error) error { if err == nil { return nil } if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok { switch pgErr.Code { case "23505": return common.Conflict("resource already exists") case "23503", "23514", "22P02": return common.BadRequest("request conflicts with stored data") } } if _, ok := errors.AsType[net.Error](err); ok || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) || pgconn.SafeToRetry(err) || errors.Is(err, pgx.ErrTxClosed) { return common.Unavailable("database unavailable") } slog.Error("unhandled database error", "err", err) return common.Internal() }