Skip to content

Commit

Permalink
chore: consistent error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
youngjun827 committed Nov 18, 2023
1 parent 724e832 commit 1962ca4
Show file tree
Hide file tree
Showing 13 changed files with 53 additions and 27 deletions.
4 changes: 3 additions & 1 deletion app/services/thoughts-api/v1/handlers/bloggrp/bloggrp.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ func New(blog *blog.Core) *Handlers {

func (h *Handlers) Create(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
var app AppNewBlog
if err := web.Decode(r, &app); err != nil {

err := web.Decode(r, &app)
if err != nil {
return response.NewError(err, http.StatusBadRequest)
}

Expand Down
4 changes: 2 additions & 2 deletions app/services/thoughts-api/v1/handlers/bloggrp/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ type Config struct {
func Routes(app *web.App, cfg Config) {
const version = "v1"

usrCore := blog.NewCore(cfg.Log, blogdb.NewStore(cfg.Log, cfg.DB))
blgCore := blog.NewCore(cfg.Log, blogdb.NewStore(cfg.Log, cfg.DB))

hdl := New(usrCore)
hdl := New(blgCore)
app.Handle(http.MethodPost, version, "/blogs", hdl.Create)
}
3 changes: 2 additions & 1 deletion app/services/thoughts-api/v1/handlers/hackgrp/hackgrp.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import (
)

func Hack(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
if n := rand.Intn(100) % 2; n == 0 {
n := rand.Intn(100) % 2
if n == 0 {
return response.NewError(errors.New("TRUST ERROR"), http.StatusBadRequest)
}

Expand Down
6 changes: 4 additions & 2 deletions app/tooling/logfmt/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ func main() {
}

traceID := "00000000-0000-0000-0000-000000000000"
if v, ok := m["trace_id"]; ok {
v, ok := m["trace_id"]
if ok {
traceID = fmt.Sprintf("%v", v)
}

Expand All @@ -67,7 +68,8 @@ func main() {
fmt.Println(out[:len(out)-2])
}

if err := scanner.Err(); err != nil {
err := scanner.Err()
if err != nil {
log.Println(err)
}
}
6 changes: 4 additions & 2 deletions app/tooling/thoughts-admin/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,17 @@ func migrateSeed() error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

if err := dbmigrate.Migrate(ctx, db); err != nil {
err = dbmigrate.Migrate(ctx, db)
if err != nil {
return fmt.Errorf("migrate database: %w", err)
}

fmt.Println("migrations complete")

// -------------------------------------------------------------------------

if err := dbmigrate.Seed(ctx, db); err != nil {
err = dbmigrate.Seed(ctx, db)
if err != nil {
return fmt.Errorf("seed database: %w", err)
}

Expand Down
15 changes: 10 additions & 5 deletions business/data/dbmigrate/dbmigrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ var (
)

func Migrate(ctx context.Context, db *sqlx.DB) error {
if err := database.StatusCheck(ctx, db); err != nil {
err := database.StatusCheck(ctx, db)
if err != nil {
return fmt.Errorf("status check database: %w", err)
}

Expand All @@ -38,7 +39,8 @@ func Migrate(ctx context.Context, db *sqlx.DB) error {
}

func Seed(ctx context.Context, db *sqlx.DB) (err error) {
if err := database.StatusCheck(ctx, db); err != nil {
err = database.StatusCheck(ctx, db)
if err != nil {
return fmt.Errorf("status check database: %w", err)
}

Expand All @@ -48,7 +50,8 @@ func Seed(ctx context.Context, db *sqlx.DB) (err error) {
}

defer func() {
if errTx := tx.Rollback(); errTx != nil {
errTx := tx.Rollback()
if errTx != nil {
if errors.Is(errTx, sql.ErrTxDone) {
return
}
Expand All @@ -57,11 +60,13 @@ func Seed(ctx context.Context, db *sqlx.DB) (err error) {
}
}()

if _, err := tx.Exec(seedDoc); err != nil {
_, err = tx.Exec(seedDoc)
if err != nil {
return fmt.Errorf("exec: %w", err)
}

if err := tx.Commit(); err != nil {
err = tx.Commit()
if err != nil {
return fmt.Errorf("commit: %w", err)
}

Expand Down
12 changes: 8 additions & 4 deletions business/data/dbsql/pgx/pgx.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ func Open(cfg Config) (*sqlx.DB, error) {
}

func StatusCheck(ctx context.Context, db *sqlx.DB) error {
if _, ok := ctx.Deadline(); !ok {
_, ok := ctx.Deadline()
if !ok {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, time.Second)
defer cancel()
Expand Down Expand Up @@ -102,14 +103,17 @@ func StatusCheck(ctx context.Context, db *sqlx.DB) error {
func NamedExecContext(ctx context.Context, log *logger.Logger, db sqlx.ExtContext, query string, data any) error {
q := queryString(query, data)

if _, ok := data.(struct{}); ok {
_, ok := data.(struct{})
if ok {
log.Infoc(ctx, 5, "database.NamedExecContext", "query", q)
} else {
log.Infoc(ctx, 4, "database.NamedExecContext", "query", q)
}

if _, err := sqlx.NamedExecContext(ctx, db, query, data); err != nil {
if pqerr, ok := err.(*pgconn.PgError); ok {
_, err := sqlx.NamedExecContext(ctx, db, query, data)
if err != nil {
pqerr, ok := err.(*pgconn.PgError)
if ok {
switch pqerr.Code {
case undefinedTable:
return ErrUndefinedTable
Expand Down
9 changes: 6 additions & 3 deletions business/web/v1/metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ func Set(ctx context.Context) context.Context {
}

func AddGoroutines(ctx context.Context) int64 {
if v, ok := ctx.Value(key).(*metrics); ok {
v, ok := ctx.Value(key).(*metrics)
if ok {
if v.requests.Value()%100 == 0 {
g := int64(runtime.NumGoroutine())
v.goroutines.Set(g)
Expand All @@ -60,7 +61,8 @@ func AddRequests(ctx context.Context) int64 {
}

func AddErrors(ctx context.Context) int64 {
if v, ok := ctx.Value(key).(*metrics); ok {
v, ok := ctx.Value(key).(*metrics)
if ok {
v.errors.Add(1)
return v.errors.Value()
}
Expand All @@ -69,7 +71,8 @@ func AddErrors(ctx context.Context) int64 {
}

func AddPanics(ctx context.Context) int64 {
if v, ok := ctx.Value(key).(*metrics); ok {
v, ok := ctx.Value(key).(*metrics)
if ok {
v.panics.Add(1)
return v.panics.Value()
}
Expand Down
6 changes: 4 additions & 2 deletions business/web/v1/mid/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import (
func Errors(log *logger.Logger) web.Middleware {
m := func(handler web.Handler) web.Handler {
h := func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
if err := handler(ctx, w, r); err != nil {
err := handler(ctx, w, r)
if err != nil {
log.Error(ctx, "message", "msg", err)

var er response.ErrorDocument
Expand Down Expand Up @@ -43,7 +44,8 @@ func Errors(log *logger.Logger) web.Middleware {
status = http.StatusInternalServerError
}

if err := web.Respond(ctx, w, er, status); err != nil {
err := web.Respond(ctx, w, er, status)
if err != nil {
return err
}

Expand Down
3 changes: 2 additions & 1 deletion business/web/v1/mid/panics.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ func Panics() web.Middleware {
h := func(ctx context.Context, w http.ResponseWriter, r *http.Request) (err error) {

defer func() {
if rec := recover(); rec != nil {
rec := recover()
if rec != nil {
trace := debug.Stack()
err = fmt.Errorf("PANIC [%v] TRACE[%s]", rec, string(trace))
metrics.AddPanics(ctx)
Expand Down
3 changes: 2 additions & 1 deletion foundation/validate/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ func init() {
}

func Check(val any) error {
if err := validate.Struct(val); err != nil {
err := validate.Struct(val)
if err != nil {

verrors, ok := err.(validator.ValidationErrors)
if !ok {
Expand Down
6 changes: 4 additions & 2 deletions foundation/web/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ type validator interface {
func Decode(r *http.Request, val any) error {
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(val); err != nil {
err := decoder.Decode(val)
if err != nil {
return fmt.Errorf("unable to decode payload: %w", err)
}

if v, ok := val.(validator); ok {
if err := v.Validate(); err != nil {
err := v.Validate()
if err != nil {
return fmt.Errorf("unable to validate payload: %w", err)
}
}
Expand Down
3 changes: 2 additions & 1 deletion foundation/web/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ func (a *App) handle(method string, group string, path string, handler Handler)
}
ctx := SetValues(r.Context(), &v)

if err := handler(ctx, w, r); err != nil {
err := handler(ctx, w, r)
if err != nil {
if validateShutdown(err) {
a.SignalShutdown()
return
Expand Down

0 comments on commit 1962ca4

Please sign in to comment.