1
0
forked from baron/baron-sso

feat(backend): backfill error code on legacy error responses

This commit is contained in:
Lectom C Han
2026-02-13 11:20:15 +09:00
parent db71364e80
commit 1bc2cfb507
3 changed files with 143 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
package middleware
import (
"baron-sso-backend/internal/response"
"encoding/json"
"strings"
"github.com/gofiber/fiber/v2"
)
// ErrorCodeEnricher injects machine-readable `code` into legacy error responses.
// This keeps backward compatibility (`error` stays) while migrating handlers
// incrementally to explicit code-based responses.
func ErrorCodeEnricher() fiber.Handler {
return func(c *fiber.Ctx) error {
err := c.Next()
body := c.Response().Body()
if len(body) == 0 {
return err
}
contentType := string(c.Response().Header.ContentType())
if contentType != "" && !strings.Contains(contentType, fiber.MIMEApplicationJSON) {
return err
}
var payload map[string]any
if unmarshalErr := json.Unmarshal(body, &payload); unmarshalErr != nil {
return err
}
if _, hasError := payload["error"]; !hasError {
return err
}
if _, hasCode := payload["code"]; hasCode {
return err
}
payload["code"] = response.StatusCode(c.Response().StatusCode())
updated, marshalErr := json.Marshal(payload)
if marshalErr != nil {
return err
}
c.Response().SetBodyRaw(updated)
return err
}
}