Skip to content

Commit

Permalink
refactor: add error middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
litsynp committed Dec 22, 2024
1 parent 029186b commit 9a0cdfb
Show file tree
Hide file tree
Showing 30 changed files with 311 additions and 295 deletions.
4 changes: 3 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ linters-settings:
# Such cases aren't reported by default.
# Default: false
check-type-assertions: true
exclude-functions:
- (*github.com/pet-sitter/pets-next-door-api/internal/infra/database.Tx).Rollback

exhaustive:
# Program elements to check for exhaustiveness.
Expand Down Expand Up @@ -490,7 +492,7 @@ linters:
- nakedret # finds naked returns in functions greater than a specified function length
- nestif # reports deeply nested if statements
- nilerr # finds the code that returns nil even if it checks that the error is not nil
- nilnil # checks that there is no simultaneous return of nil error and an invalid value
# - nilnil # checks that there is no simultaneous return of nil error and an invalid value
- noctx # finds sending http request without context.Context
- nolintlint # reports ill-formed or insufficient nolint directives
- nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL
Expand Down
4 changes: 4 additions & 0 deletions api/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ type AppError struct {
Message string `json:"message,omitempty"`
}

func (e *AppError) Error() string {
return e.Message
}

func NewAppError(err error, statusCode int, code AppErrorCode, message string) *AppError {
log.Error().Err(err).Msg(message)
return &AppError{
Expand Down
14 changes: 7 additions & 7 deletions api/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/labstack/echo/v4"
)

func ParseBody(c echo.Context, payload interface{}) *AppError {
func ParseBody(c echo.Context, payload interface{}) error {
if err := c.Bind(payload); err != nil {
return ErrInvalidBody(err)
}
Expand All @@ -22,7 +22,7 @@ func ParseBody(c echo.Context, payload interface{}) *AppError {
return nil
}

func ParseIDFromPath(c echo.Context, path string) (uuid.UUID, *AppError) {
func ParseIDFromPath(c echo.Context, path string) (uuid.UUID, error) {
idStr := c.Param(path)
id, err := uuid.Parse(idStr)
if err != nil {
Expand All @@ -32,7 +32,7 @@ func ParseIDFromPath(c echo.Context, path string) (uuid.UUID, *AppError) {
return id, nil
}

func ParseOptionalUUIDQuery(c echo.Context, query string) (uuid.NullUUID, *AppError) {
func ParseOptionalUUIDQuery(c echo.Context, query string) (uuid.NullUUID, error) {
queryStr := c.QueryParam(query)
if queryStr == "" {
return uuid.NullUUID{}, nil
Expand All @@ -48,7 +48,7 @@ func ParseOptionalUUIDQuery(c echo.Context, query string) (uuid.NullUUID, *AppEr
return uuid.NullUUID{UUID: id, Valid: true}, nil
}

func ParseOptionalIntQuery(c echo.Context, query string) (*int, *AppError) {
func ParseOptionalIntQuery(c echo.Context, query string) (*int, error) {
queryStr := c.QueryParam(query)
if queryStr == "" {
return nil, nil
Expand All @@ -62,7 +62,7 @@ func ParseOptionalIntQuery(c echo.Context, query string) (*int, *AppError) {
return &value, nil
}

func ParseRequiredStringQuery(c echo.Context, query string) (*string, *AppError) {
func ParseRequiredStringQuery(c echo.Context, query string) (*string, error) {
queryStr := c.QueryParam(query)
if queryStr == "" {
return nil, ErrInvalidQuery(fmt.Errorf("expected non-empty string for query: %s", query))
Expand All @@ -84,7 +84,7 @@ func ParseOptionalStringQuery(c echo.Context, query string) *string {
func ParsePaginationQueries(
c echo.Context,
defaultPage, defaultLimit int,
) (page, size int, err *AppError) {
) (page, size int, err error) {
pageQuery := c.QueryParam("page")
sizeQuery := c.QueryParam("size")

Expand Down Expand Up @@ -116,7 +116,7 @@ func ParsePaginationQueries(

func ParseCursorPaginationQueries(
c echo.Context, defaultLimit int,
) (prev, next uuid.NullUUID, limit int, err *AppError) {
) (prev, next uuid.NullUUID, limit int, err error) {
prevQuery := c.QueryParam("prev")
nextQuery := c.QueryParam("next")
sizeQuery := c.QueryParam("size")
Expand Down
2 changes: 1 addition & 1 deletion cmd/import_breeds/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ func parseFlags() Flags {

func importBreed(
ctx context.Context, conn *database.DB, petType commonvo.PetType, row breedsimporterservice.Row,
) (*breed.DetailView, *pnd.AppError) {
) (*breed.DetailView, error) {
log.Printf("Importing breed with pet_type: %s, name: %s to database", petType, row.Breed)

existingList, err := databasegen.New(conn).FindBreeds(ctx, databasegen.FindBreedsParams{
Expand Down
6 changes: 3 additions & 3 deletions cmd/import_conditions/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ func main() {
ctx := context.Background()

conditionService := service.NewSOSConditionService(db)
conditionList, err2 := conditionService.InitConditions(ctx)
if err2 != nil {
log.Fatalf("error initializing conditions: %v\n", err2)
conditionList, err := conditionService.InitConditions(ctx)
if err != nil {
log.Fatalf("error initializing conditions: %v\n", err)
}

log.Println("Total conditions imported: ", len(conditionList))
Expand Down
2 changes: 1 addition & 1 deletion cmd/migrateuuids/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func main() {

pndErr := migrate(ctx, db, MigrateOptions{ReadOnly: *readOnlyPtr, Force: *forcePtr})
if pndErr != nil {
panic(pndErr.Err)
panic(pndErr)
}

log.Println("Completed migration")
Expand Down
6 changes: 3 additions & 3 deletions cmd/migrateuuids/uuidmigrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ type MigrateOptions struct {
Log bool
}

func migrate(ctx context.Context, db *database.DB, options MigrateOptions) *pnd.AppError {
func migrate(ctx context.Context, db *database.DB, options MigrateOptions) error {
log.Println("Migrating UUIDs for tables")
tx, err := db.BeginTx(ctx)
if err != nil {
Expand Down Expand Up @@ -210,7 +210,7 @@ func migrate(ctx context.Context, db *database.DB, options MigrateOptions) *pnd.
return nil
}

func MigrateUUID(tx *database.Tx, options MigrateOptions) *pnd.AppError {
func MigrateUUID(tx *database.Tx, options MigrateOptions) error {
type Row struct {
ID int
UUID *string
Expand Down Expand Up @@ -309,7 +309,7 @@ func MigrateUUID(tx *database.Tx, options MigrateOptions) *pnd.AppError {
}

// FK 컬럼을 연관된 테이블의 uuid 컬럼을 조회해 업데이트
func MigrateFK(tx *database.Tx, options MigrateOptions) *pnd.AppError {
func MigrateFK(tx *database.Tx, options MigrateOptions) error {
for _, target := range Targets {
log.Printf("Processing table %s\n", target.Table)

Expand Down
17 changes: 8 additions & 9 deletions cmd/server/handler/auth_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@ func (h *AuthHandler) KakaoCallback(c echo.Context) error {
return c.JSON(pndErr.StatusCode, pndErr)
}

customToken, err2 := h.authService.CustomToken(
customToken, err := h.authService.CustomToken(
c.Request().Context(),
strconv.FormatInt(userProfile.ID, 10),
)
if err2 != nil {
return c.JSON(err2.StatusCode, err2)
if err != nil {
return err
}

return c.JSON(http.StatusOK, auth.NewKakaoCallbackView(*customToken, userProfile))
Expand All @@ -90,24 +90,23 @@ func (h *AuthHandler) KakaoCallback(c echo.Context) error {
func (h *AuthHandler) GenerateFBCustomTokenFromKakao(c echo.Context) error {
var tokenRequest auth.GenerateFBCustomTokenRequest
if err := pnd.ParseBody(c, &tokenRequest); err != nil {
return c.JSON(err.StatusCode, err)
return err
}

userProfile, err2 := h.kakaoClient.FetchUserProfile(
userProfile, err := h.kakaoClient.FetchUserProfile(
c.Request().Context(),
tokenRequest.OAuthToken,
)
if err2 != nil {
pndErr := pnd.ErrBadRequest(errors.New("유효하지 않은 Kakao 인증 정보입니다"))
return c.JSON(pndErr.StatusCode, pndErr)
if err != nil {
return pnd.ErrBadRequest(errors.New("유효하지 않은 Kakao 인증 정보입니다"))
}

customToken, err := h.authService.CustomToken(
c.Request().Context(),
strconv.FormatInt(userProfile.ID, 10),
)
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

return c.JSON(
Expand Down
4 changes: 2 additions & 2 deletions cmd/server/handler/breed_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func (h *BreedHandler) FindBreeds(c echo.Context) error {
petType := pnd.ParseOptionalStringQuery(c, "pet_type")
page, size, err := pnd.ParsePaginationQueries(c, 1, 20)
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

res, err := h.breedService.FindBreeds(c.Request().Context(), &breed.FindBreedsParams{
Expand All @@ -42,7 +42,7 @@ func (h *BreedHandler) FindBreeds(c echo.Context) error {
PetType: petType,
})
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

return c.JSON(http.StatusOK, res)
Expand Down
36 changes: 18 additions & 18 deletions cmd/server/handler/chat_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ func (h ChatHandler) FindRoomByID(c echo.Context) error {
c.Request().Header.Get("Authorization"),
)
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

roomID, err := pnd.ParseIDFromPath(c, "roomID")
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

res, err := h.chatService.FindChatRoomByUIDAndRoomID(
Expand All @@ -54,7 +54,7 @@ func (h ChatHandler) FindRoomByID(c echo.Context) error {
roomID,
)
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

return c.JSON(http.StatusOK, res)
Expand All @@ -76,12 +76,12 @@ func (h ChatHandler) CreateRoom(c echo.Context) error {
c.Request().Header.Get("Authorization"),
)
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}
var createRoomRequest domain.CreateRoomRequest

if bodyError := pnd.ParseBody(c, &createRoomRequest); bodyError != nil {
return c.JSON(bodyError.StatusCode, err)
return err
}

res, err := h.chatService.CreateRoom(
Expand All @@ -91,7 +91,7 @@ func (h ChatHandler) CreateRoom(c echo.Context) error {
user.FirebaseUID,
)
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

return c.JSON(http.StatusCreated, res)
Expand All @@ -113,17 +113,17 @@ func (h ChatHandler) JoinChatRoom(c echo.Context) error {
c.Request().Header.Get("Authorization"),
)
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

roomID, err := pnd.ParseIDFromPath(c, "roomID")
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

res, err := h.chatService.JoinRoom(c.Request().Context(), roomID, foundUser.FirebaseUID)
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

return c.JSON(http.StatusOK, res)
Expand All @@ -145,12 +145,12 @@ func (h ChatHandler) LeaveChatRoom(c echo.Context) error {
c.Request().Header.Get("Authorization"),
)
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

roomID, err := pnd.ParseIDFromPath(c, "roomID")
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

res := h.chatService.LeaveRoom(c.Request().Context(), roomID, foundUser.FirebaseUID)
Expand All @@ -172,12 +172,12 @@ func (h ChatHandler) FindAllRooms(c echo.Context) error {
c.Request().Header.Get("Authorization"),
)
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

rooms, err := h.chatService.FindAllByUserUID(c.Request().Context(), foundUser.FirebaseUID)
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}
return c.JSON(http.StatusOK, rooms)
}
Expand All @@ -198,12 +198,12 @@ func (h ChatHandler) FindAllRooms(c echo.Context) error {
func (h ChatHandler) FindMessagesByRoomID(c echo.Context) error {
roomID, err := pnd.ParseIDFromPath(c, "roomID")
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

prev, next, limit, appError := pnd.ParseCursorPaginationQueries(c, 30)
if appError != nil {
return c.JSON(appError.StatusCode, appError)
prev, next, limit, err := pnd.ParseCursorPaginationQueries(c, 30)
if err != nil {
return err
}

res, err := h.chatService.FindChatRoomMessagesByRoomID(
Expand All @@ -214,7 +214,7 @@ func (h ChatHandler) FindMessagesByRoomID(c echo.Context) error {
int64(limit),
)
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

return c.JSON(http.StatusOK, res)
Expand Down
2 changes: 1 addition & 1 deletion cmd/server/handler/condition_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func NewConditionHandler(conditionService service.SOSConditionService) *Conditio
func (h *ConditionHandler) FindConditions(c echo.Context) error {
res, err := h.conditionService.FindConditions(c.Request().Context())
if err != nil {
return c.JSON(err.StatusCode, err)
return err
}

return c.JSON(http.StatusOK, res)
Expand Down
Loading

0 comments on commit 9a0cdfb

Please sign in to comment.