Add structured logging and centralized error handling

- Initialize slog in the serve command with terminal/file support
- Introduce `AppError` with HTTP status for unified service-layer errors
- Replace ad-hoc `api.Error` calls with `api.RespondError`
- Wrap internal errors with `model.NewInternalError` and add reference
  IDs
- Add `RequestID` middleware and switch router from `gin.Default` to
  `gin.New`
This commit is contained in:
2026-07-04 16:24:22 +08:00
parent a78d43b166
commit 1dfccf513a
16 changed files with 281 additions and 134 deletions
+13 -8
View File
@@ -1,6 +1,7 @@
package handler
import (
"log/slog"
"net/http"
"github.com/gin-gonic/gin"
@@ -38,13 +39,14 @@ type tokenRequest struct {
func (h *AuthHandler) Register(c *gin.Context) {
var req registerRequest
if err := c.ShouldBindJSON(&req); err != nil {
api.Error(c, http.StatusBadRequest, "invalid request: "+err.Error())
slog.DebugContext(c.Request.Context(), "register bind failed", "error", err)
api.Error(c, http.StatusBadRequest, "invalid request body")
return
}
user, err := h.authService.Register(c.Request.Context(), req.Username, req.Email, req.Password)
if err != nil {
api.Error(c, http.StatusConflict, err.Error())
api.RespondError(c, err)
return
}
@@ -55,13 +57,14 @@ func (h *AuthHandler) Register(c *gin.Context) {
func (h *AuthHandler) Login(c *gin.Context) {
var req loginRequest
if err := c.ShouldBindJSON(&req); err != nil {
api.Error(c, http.StatusBadRequest, "invalid request: "+err.Error())
slog.DebugContext(c.Request.Context(), "login bind failed", "error", err)
api.Error(c, http.StatusBadRequest, "invalid request body")
return
}
pair, err := h.authService.Login(c.Request.Context(), req.Email, req.Password)
if err != nil {
api.Error(c, http.StatusUnauthorized, err.Error())
api.RespondError(c, err)
return
}
@@ -72,13 +75,14 @@ func (h *AuthHandler) Login(c *gin.Context) {
func (h *AuthHandler) Refresh(c *gin.Context) {
var req tokenRequest
if err := c.ShouldBindJSON(&req); err != nil {
api.Error(c, http.StatusBadRequest, "invalid request: "+err.Error())
slog.DebugContext(c.Request.Context(), "refresh bind failed", "error", err)
api.Error(c, http.StatusBadRequest, "invalid request body")
return
}
pair, err := h.authService.Refresh(c.Request.Context(), req.RefreshToken)
if err != nil {
api.Error(c, http.StatusUnauthorized, err.Error())
api.RespondError(c, err)
return
}
@@ -89,12 +93,13 @@ func (h *AuthHandler) Refresh(c *gin.Context) {
func (h *AuthHandler) Logout(c *gin.Context) {
var req tokenRequest
if err := c.ShouldBindJSON(&req); err != nil {
api.Error(c, http.StatusBadRequest, "invalid request: "+err.Error())
slog.DebugContext(c.Request.Context(), "logout bind failed", "error", err)
api.Error(c, http.StatusBadRequest, "invalid request body")
return
}
if err := h.authService.Logout(c.Request.Context(), req.RefreshToken); err != nil {
api.Error(c, http.StatusInternalServerError, err.Error())
api.RespondError(c, err)
return
}