Skip to content

Commit

Permalink
feat(api): implement error handling middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
youngjun827 committed Nov 7, 2023
1 parent 377a6f5 commit 51d7e40
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 2 deletions.
7 changes: 7 additions & 0 deletions app/services/thoughts-api/v1/handlers/hackgrp/hackgrp.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,19 @@ package hackgrp

import (
"context"
"errors"
"math/rand"
"net/http"

"github.com/youngjun827/thoughts/business/web/v1/response"
"github.com/youngjun827/thoughts/foundation/web"
)

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

status := struct {
Status string
}{
Expand Down
52 changes: 52 additions & 0 deletions business/web/v1/mid/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package mid

import (
"context"
"net/http"

"github.com/youngjun827/thoughts/business/web/v1/response"
"github.com/youngjun827/thoughts/foundation/logger"
"github.com/youngjun827/thoughts/foundation/web"
)

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 {
log.Error(ctx, "message", "msg", err)

var er response.ErrorDocument
var status int

switch {
case response.IsError(err):
reqErr := response.GetError(err)
er = response.ErrorDocument{
Error: reqErr.Error(),
}
status = reqErr.Status

default:
er = response.ErrorDocument{
Error: http.StatusText(http.StatusInternalServerError),
}
status = http.StatusInternalServerError
}

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

if web.IsShutdown(err) {
return err
}
}

return nil
}

return h
}

return m
}
2 changes: 1 addition & 1 deletion business/web/v1/v1.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type RouteAdder interface {
}

func APIMux(cfg APIMuxConfig, routeAdder RouteAdder) chi.Router {
app := web.NewApp(cfg.Shutdown, mid.Logger(cfg.Log))
app := web.NewApp(cfg.Shutdown, mid.Logger(cfg.Log), mid.Errors(cfg.Log))

routeAdder.Add(app.Mux, cfg)

Expand Down
1 change: 0 additions & 1 deletion foundation/web/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ func HandlerAdapter(handler Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := handler(r.Context(), w, r)
if err != nil {
// Handle the error as needed
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
Expand Down

0 comments on commit 51d7e40

Please sign in to comment.