Skip to content

Commit

Permalink
feat: implement custom HTTP error handling
Browse files Browse the repository at this point in the history
Add a custom HTTP error handler to improve error response formatting and ensure internal errors are properly reported. Disable error forwarding in the request logger middleware to allow for centralized error handling.
  • Loading branch information
vaayne committed Sep 6, 2024
1 parent 11dd82a commit b7f84b2
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
2 changes: 1 addition & 1 deletion internal/port/httpserver/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func requestLoggerMiddleware() echo.MiddlewareFunc {
LogRequestID: true,
LogReferer: true,
LogHeaders: []string{},
HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code
HandleError: false,
LogValuesFunc: logValuesFunc,
})
}
Expand Down
21 changes: 19 additions & 2 deletions internal/port/httpserver/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,29 @@ func JsonResponse(c echo.Context, code int, data interface{}) error {
}

func ErrorResponse(c echo.Context, code int, err error) error {
return echo.NewHTTPError(code).SetInternal(err)
}

func customHTTPErrorHandler(err error, c echo.Context) {
if c.Response().Committed {
return
}

code := http.StatusInternalServerError
msg := err.Error()

he, ok := err.(*echo.HTTPError)
if ok {
code = he.Code
if he.Internal != nil {
msg = he.Internal.Error()
}
}
_ = c.JSON(code, JSONResult{
Success: false,
Code: code,
Message: err.Error(),
Message: msg,
})
return err
}

// bindAndValidate binds the request data to the provided struct and validates it.
Expand Down
1 change: 1 addition & 0 deletions internal/port/httpserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ func New(pool *db.Pool, llm *llms.LLM, queue *queue.Queue, opts ...Option) (*Ser
queue: queue,
}
s.Server.Validator = &CustomValidator{validator: validator.New()}
s.Server.HTTPErrorHandler = customHTTPErrorHandler
// if config.Settings.DebugUI {
// logger.Default.Info("debug ui enabled")
// s.uiCmd = exec.Command("bun", "run", "dev")
Expand Down

0 comments on commit b7f84b2

Please sign in to comment.