diff --git a/backend/db/db.go b/backend/db/db.go index f5301ca..a535b7f 100644 --- a/backend/db/db.go +++ b/backend/db/db.go @@ -2,11 +2,13 @@ package db import ( "context" + "errors" "fmt" "net/http" "time" "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" ) @@ -48,3 +50,29 @@ func transaction(handler func(context.Context, pgx.Tx) (statusCode int, err erro } return } + +// Handle database error +func handleDBError(errIn error) (statusCode int, err error) { + if errIn == nil { + return + } + if errors.Is(errIn, pgx.ErrNoRows) { + err = fmt.Errorf("not found") + statusCode = http.StatusNotFound + return + } + var pgErr *pgconn.PgError + if errors.As(errIn, &pgErr) { + switch pgErr.Code { + case "22P02", "22007": // Invalid data format + err = fmt.Errorf("%s", pgErr.Message) + statusCode = http.StatusBadRequest + return + case "23505": // Unique constraint violation + err = fmt.Errorf("already exists") + statusCode = http.StatusConflict + return + } + } + return http.StatusInternalServerError, errIn +}