-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
move repetitive error checking to helper functions
- Loading branch information
1 parent
394b5cd
commit 5e33594
Showing
3 changed files
with
91 additions
and
124 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,46 @@ | ||
package server | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
|
||
"github.com/jackc/pgx/v5/pgtype" | ||
"github.com/labstack/echo/v4" | ||
) | ||
|
||
func validateBody(c echo.Context, requestBodyType interface{}) error { | ||
if err := c.Bind(requestBodyType); err != nil { | ||
return echo.NewHTTPError(http.StatusBadRequest, "Invalid request body :(") | ||
} | ||
|
||
if err := c.Validate(requestBodyType); err != nil { | ||
return echo.NewHTTPError(http.StatusBadRequest, err.Error()) | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func validateUUID(id string, fieldName string) (pgtype.UUID, error) { | ||
var uuid pgtype.UUID | ||
if id == "" { | ||
return uuid, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Missing %s ID :(", fieldName)) | ||
} | ||
|
||
if err := uuid.Scan(id); err != nil { | ||
return uuid, echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Invalid %s ID format :(", fieldName)) | ||
} | ||
|
||
return uuid, nil | ||
} | ||
|
||
func handleDBError(err error, operation string, resourceType string) error { | ||
if isNoRowsError(err) { | ||
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("%s not found :(", resourceType)) | ||
} | ||
|
||
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to %s %s :(", operation, resourceType)) | ||
} | ||
|
||
func isNoRowsError(err error) bool { | ||
return err != nil && err.Error() == "no rows in dis set" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters