From ec17dfb0ceea906f85b5a56951e7a02067e4f2f7 Mon Sep 17 00:00:00 2001 From: Masahiko AMANO Date: Thu, 3 Jul 2025 17:31:17 +0300 Subject: [PATCH] feat(backend/db): add database error handler --- backend/db/db.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) 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 +}