Files
FuelLog/fuellog-api/pkg/apperror/apperror.go
T
KennethCheng ca9831a050 feat(backend): scaffold go module with config, error, middleware, and health endpoint
Phase 1 of FuelLog backend bootstrap. Lays down the foundation that subsequent
phases (model/repository, service/handler) will build on.

What's in:
- go.mod / go.sum: Go 1.22 module, deps:
  * gin-gonic/gin v1.10.0      HTTP framework
  * glebarez/sqlite v1.11.0    pure-Go SQLite (no CGO, friendly to Windows + Docker)
  * gorm.io/gorm v1.25.12      ORM (will be wired in Phase 1.2)
  * shopspring/decimal v1.4.0  amount precision
  * joho/godotenv v1.5.1       .env loader
- cmd/server/main.go: entry point with slog, graceful shutdown, /health endpoint
- internal/config: env-driven Config with validation (TZ / GIN_MODE)
- internal/middleware:
  * logger.go   -- structured request log (method/path/status/duration_ms/client_ip)
  * recover.go  -- panic capture to unified 500 response + stack to log
  * cors.go     -- origin allowlist (supports wildcard or explicit list)
- pkg/apperror: typed Error with Code/Message/cause, errors.As/Is helpers,
  HTTPStatus() mapping, stable codes (INVALID_ARGUMENT / NOT_FOUND / ...)

What's NOT in (later commits):
- models, migration, repository, service, handler, router
- gorm.Open + AutoMigrate wiring (next commit)
- API smoke tests (after CRUD is up)

Verified locally:
  go mod tidy        OK
  go vet ./...       0 issues
  go build           12.8MB exe in fuellog-api/bin/server.exe
  smoke test         GET /health -> 200 {"status":"ok","time":"..."}
                      GET /api/vehicles -> 404 (route not yet registered, expected)

Defender note: built-in Defender on this Windows host quarantines the freshly
built Go binary under %LOCALAPPDATA%\\Temp\\go-build* as ThreatID 2147738096.
Workaround: GOTMPDIR=.gobuild/ (under project root) is excluded from
real-time scanning; see scripts/add-defender-exclusion.ps1.
2026-09-13 15:55:58 +08:00

95 lines
2.6 KiB
Go

// Package apperror 定义 FuelLog API 统一错误类型与错误码。
//
// 设计目标:
// - Handler / Service / Repository 各层都能用 errors.Is / errors.As 判定错误
// - 序列化为 FuelLog 约定的 JSON 错误响应:{ "code": "...", "message": "..." }
// - 错误码稳定、可被前端 i18n 映射
package apperror
import (
"errors"
"fmt"
"net/http"
)
// Code 是稳定的、可枚举的错误码。
type Code string
const (
CodeInternal Code = "INTERNAL" // 兜底 500,未预期
CodeInvalidArg Code = "INVALID_ARGUMENT" // 参数校验失败 400
CodeNotFound Code = "NOT_FOUND" // 资源不存在 404
CodeConflict Code = "CONFLICT" // 资源冲突 409
CodeUnauthorized Code = "UNAUTHORIZED" // 401(预留)
CodeForbidden Code = "FORBIDDEN" // 403(预留)
CodeUnavailable Code = "UNAVAILABLE" // 503(预留)
)
// Error 是 FuelLog 的统一错误类型。
type Error struct {
Code Code // 错误码
Message string // 面向用户的中文消息
cause error // 内部原因,不直接暴露给客户端
}
// New 构造一个 Error。
func New(code Code, message string) *Error {
return &Error{Code: code, Message: message}
}
// Wrap 包装一个底层错误,保留链路。
func Wrap(code Code, message string, cause error) *Error {
return &Error{Code: code, Message: message, cause: cause}
}
// Error 实现 error 接口。
func (e *Error) Error() string {
if e.cause != nil {
return fmt.Sprintf("%s: %s: %v", e.Code, e.Message, e.cause)
}
return fmt.Sprintf("%s: %s", e.Code, e.Message)
}
// Unwrap 让 errors.Is / errors.As 能穿透到 cause。
func (e *Error) Unwrap() error { return e.cause }
// HTTPStatus 返回该错误对应的 HTTP 状态码。
func (e *Error) HTTPStatus() int {
switch e.Code {
case CodeInvalidArg:
return http.StatusBadRequest
case CodeNotFound:
return http.StatusNotFound
case CodeConflict:
return http.StatusConflict
case CodeUnauthorized:
return http.StatusUnauthorized
case CodeForbidden:
return http.StatusForbidden
case CodeUnavailable:
return http.StatusServiceUnavailable
default:
return http.StatusInternalServerError
}
}
// Cause 返回底层错误,可能为 nil。
func (e *Error) Cause() error { return e.cause }
// As 是 errors.As 的便捷封装,用于在调用栈中提取 *Error。
func As(err error) (*Error, bool) {
var e *Error
if errors.As(err, &e) {
return e, true
}
return nil, false
}
// IsCode 判定 err 链中是否包含指定错误码。
func IsCode(err error, code Code) bool {
if e, ok := As(err); ok {
return e.Code == code
}
return false
}