Skip to content

Commit

Permalink
chore: handle Postgres error from error middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
litsynp committed Dec 22, 2024
1 parent 9a0cdfb commit 03882e7
Show file tree
Hide file tree
Showing 11 changed files with 110 additions and 129 deletions.
4 changes: 3 additions & 1 deletion api/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,9 @@ func FromPostgresError(err error) *AppError {
return NewAppError(err, http.StatusBadRequest, ErrCodeBadRequest, "잘못된 값입니다")
case strings.Contains(errStr, "violates unique constraint"):
return NewAppError(err, http.StatusConflict, ErrCodeConflict, "중복된 값입니다")
default:
case strings.Contains(errStr, "pq:"):
return NewAppError(err, http.StatusInternalServerError, ErrCodeUnknown, "알 수 없는 오류가 발생했습니다")
default:
return nil
}
}
5 changes: 2 additions & 3 deletions cmd/import_breeds/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (

"github.com/pet-sitter/pets-next-door-api/cmd/import_breeds/breedsimporterservice"

pnd "github.com/pet-sitter/pets-next-door-api/api"
"github.com/pet-sitter/pets-next-door-api/internal/configs"
"github.com/pet-sitter/pets-next-door-api/internal/infra/database"
)
Expand Down Expand Up @@ -103,7 +102,7 @@ func importBreed(
Name: utils.StrToNullStr(row.Breed),
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

if len(existingList) > 1 {
Expand All @@ -123,7 +122,7 @@ func importBreed(
PetType: petType.String(),
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

log.Printf(
Expand Down
6 changes: 6 additions & 0 deletions cmd/server/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,12 @@ func NewRouter(app *firebaseinfra.FirebaseApp) (*echo.Echo, error) {
return c.JSON(appErr.StatusCode, appErr)
}

if err := pnd.FromPostgresError(err); err != nil {
if errors.As(err, &appErr) {
return c.JSON(appErr.StatusCode, appErr)
}
}

return c.JSON(http.StatusInternalServerError, pnd.ErrUnknown(err))
}

Expand Down
4 changes: 1 addition & 3 deletions internal/common/null.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package utils
import (
"database/sql"
"time"

pnd "github.com/pet-sitter/pets-next-door-api/api"
)

func DerefOrEmpty[T any](val *T) T {
Expand Down Expand Up @@ -106,7 +104,7 @@ func StrToNullTime(val string) (sql.NullTime, error) {
if err != nil {
return sql.NullTime{
Valid: false,
}, pnd.FromPostgresError(err)
}, err
}
return sql.NullTime{
Time: parsedTime,
Expand Down
12 changes: 3 additions & 9 deletions internal/infra/database/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import (
"database/sql"
"errors"

pnd "github.com/pet-sitter/pets-next-door-api/api"

"github.com/rs/zerolog/log"
)

Expand All @@ -20,7 +18,7 @@ type Transactioner interface {
func (db *DB) BeginTx(ctx context.Context) (*Tx, error) {
tx, err := db.DB.BeginTx(ctx, nil)
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

return &Tx{tx}, nil
Expand Down Expand Up @@ -54,18 +52,14 @@ func (tx *Tx) Rollback() error {
if errors.Is(err, sql.ErrTxDone) {
return nil
}
return pnd.FromPostgresError(err)
return err
}

return nil
}

func (tx *Tx) Commit() error {
if err := tx.Tx.Commit(); err != nil {
return pnd.FromPostgresError(err)
}

return nil
return tx.Tx.Commit()
}

func WithTransaction(ctx context.Context, conn *DB, f func(tx *Tx) error) error {
Expand Down
3 changes: 1 addition & 2 deletions internal/service/breed_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (

databasegen "github.com/pet-sitter/pets-next-door-api/internal/infra/database/gen"

pnd "github.com/pet-sitter/pets-next-door-api/api"
"github.com/pet-sitter/pets-next-door-api/internal/domain/breed"
"github.com/pet-sitter/pets-next-door-api/internal/infra/database"
)
Expand All @@ -25,7 +24,7 @@ func (s *BreedService) FindBreeds(
) (*breed.ListView, error) {
rows, err := databasegen.New(s.conn).FindBreeds(ctx, params.ToDBParams())
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

return breed.ToListViewFromRows(params.Page, params.Size, rows), nil
Expand Down
66 changes: 31 additions & 35 deletions internal/service/chat_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func (s *ChatService) CreateRoom(
FbUid: utils.StrToNullStr(userFirebaseUID),
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

// 채팅방 생성
Expand All @@ -50,14 +50,13 @@ func (s *ChatService) CreateRoom(
}

q := databasegen.New(tx)
row, databaseGenError := q.CreateRoom(ctx, databasegen.CreateRoomParams{
row, err := q.CreateRoom(ctx, databasegen.CreateRoomParams{
ID: chatRoomUUID,
Name: name,
RoomType: roomType,
})

if databaseGenError != nil {
return nil, pnd.FromPostgresError(databaseGenError)
if err != nil {
return nil, err
}

joinRoomUUID, joinRoomUUIDError := uuid.NewV7()
Expand All @@ -71,7 +70,7 @@ func (s *ChatService) CreateRoom(
RoomID: row.ID,
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

if err := tx.Commit(); err != nil {
Expand All @@ -90,13 +89,12 @@ func (s *ChatService) JoinRoom(
FbUid: utils.StrToNullStr(fbUID),
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}
// 채팅방이 현재 존재하는지 확인
existRoom, existRoomError := databasegen.New(s.conn).ExistsRoom(ctx, roomID)

if existRoomError != nil {
return nil, pnd.FromPostgresError(existRoomError)
existRoom, err := databasegen.New(s.conn).ExistsRoom(ctx, roomID)
if err != nil {
return nil, err
}

if !existRoom {
Expand All @@ -106,7 +104,7 @@ func (s *ChatService) JoinRoom(
// 채팅방에 이미 참여중인지 확인
existsUser, existsUserError := databasegen.New(s.conn).UserExistsInRoom(ctx, roomID)
if existsUserError != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

// 채팅방에 참여하지 않은 경우 참여
Expand All @@ -123,7 +121,7 @@ func (s *ChatService) JoinRoom(
UserID: userData.ID,
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

return chat.ToJoinRoom(row), nil
Expand All @@ -137,25 +135,25 @@ func (s *ChatService) LeaveRoom(ctx context.Context, roomID uuid.UUID, fbUID str
FbUid: utils.StrToNullStr(fbUID),
})
if err != nil {
return pnd.FromPostgresError(err)
return err
}

err = databasegen.New(s.conn).LeaveRoom(ctx, databasegen.LeaveRoomParams{
RoomID: roomID,
UserID: userData.ID,
})
if err != nil {
return pnd.FromPostgresError(err)
return err
}
exists, err := databasegen.New(s.conn).UserExistsInRoom(ctx, roomID)
if err != nil {
return pnd.FromPostgresError(err)
return err
}

if !exists {
err = databasegen.New(s.conn).DeleteRoom(ctx, roomID)
if err != nil {
return pnd.FromPostgresError(err)
return err
}
}
return nil
Expand All @@ -169,11 +167,11 @@ func (s *ChatService) FindAllByUserUID(
FbUid: utils.StrToNullStr(fbUID),
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}
rows, err := databasegen.New(s.conn).FindAllUserChatRoomsByUserUID(ctx, userData.ID)
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

// rows를 반복하며 각 row에 대해 ToJoinRoom을 호출하여 JoinRoom으로 변환
Expand All @@ -191,15 +189,15 @@ func (s *ChatService) FindChatRoomByUIDAndRoomID(
FbUid: utils.StrToNullStr(fbUID),
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

row, err := databasegen.New(s.conn).FindRoomByIDAndUserID(
ctx,
databasegen.FindRoomByIDAndUserIDParams{ID: roomID, UserID: userData.ID},
)
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

return chat.ToUserChatRoomView(row), nil
Expand All @@ -224,7 +222,7 @@ func (s *ChatService) FindChatRoomMessagesByRoomID(
RoomID: roomID,
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

// rows의 맨 앞의 ID값을 가져온다.
Expand All @@ -239,24 +237,22 @@ func (s *ChatService) FindChatRoomMessagesByRoomID(
// 가장 오래된 메시지의 ID를 가져온다.
lastID := rows[len(rows)-1].ID

hasPrev, hasPrevError := databasegen.New(s.conn).
hasPrev, err := databasegen.New(s.conn).
HasPrevMessages(ctx, databasegen.HasPrevMessagesParams{
ID: lastID,
RoomID: roomID,
})

if hasPrevError != nil {
return nil, pnd.FromPostgresError(hasPrevError)
if err != nil {
return nil, err
}

hasNext, hasNextError := databasegen.New(s.conn).
hasNext, err := databasegen.New(s.conn).
HasNextMessages(ctx, databasegen.HasNextMessagesParams{
ID: firstID,
RoomID: roomID,
})

if hasNextError != nil {
return nil, pnd.FromPostgresError(hasNextError)
if err != nil {
return nil, err
}

return chat.ToUserChatRoomMessageBetweenView(rows, hasNext, hasPrev, &firstID, &lastID), nil
Expand All @@ -271,7 +267,7 @@ func (s *ChatService) FindChatRoomMessagesByRoomID(
RoomID: roomID,
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

if len(rows) == 0 {
Expand Down Expand Up @@ -304,7 +300,7 @@ func (s *ChatService) FindChatRoomMessagesByRoomID(
RoomID: roomID,
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

if len(rows) == 0 {
Expand Down Expand Up @@ -335,7 +331,7 @@ func (s *ChatService) FindChatRoomMessagesByRoomID(
RoomID: roomID,
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

if len(rows) == 0 {
Expand Down Expand Up @@ -368,7 +364,7 @@ func (s *ChatService) HasPrevMessages(
RoomID: roomID,
})
if err != nil {
return false, pnd.FromPostgresError(err)
return false, err
}

return hasPrev, nil
Expand All @@ -383,7 +379,7 @@ func (s *ChatService) HasNextMessages(
RoomID: roomID,
})
if err != nil {
return false, pnd.FromPostgresError(err)
return false, err
}

return hasNext, nil
Expand Down
7 changes: 3 additions & 4 deletions internal/service/media_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (

databasegen "github.com/pet-sitter/pets-next-door-api/internal/infra/database/gen"

pnd "github.com/pet-sitter/pets-next-door-api/api"
"github.com/pet-sitter/pets-next-door-api/internal/domain/media"
"github.com/pet-sitter/pets-next-door-api/internal/infra/database"
)
Expand Down Expand Up @@ -65,7 +64,7 @@ func (s *MediaService) CreateMedia(
Url: url,
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

if err := tx.Commit(); err != nil {
Expand All @@ -83,7 +82,7 @@ func (s *MediaService) FindMediaByID(
ID: uuid.NullUUID{UUID: id, Valid: true},
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}

return media.ToDetailView(mediaData), nil
Expand All @@ -106,7 +105,7 @@ func (s *MediaService) FindMediasByIDs(
IncludeDeleted: false,
})
if err != nil {
return nil, pnd.FromPostgresError(err)
return nil, err
}
views := make([]media.DetailView, 0)
for _, mediaData := range mediaDataList {
Expand Down
Loading

0 comments on commit 03882e7

Please sign in to comment.