package handler import ( "errors" "fmt" "net/http" "bj_power_wms/internal/verr" "github.com/zeromicro/go-zero/rest/httpx" ) // 统一响应结构:{ code, message, data } type Response struct { Code int `json:"code"` Message string `json:"message"` Data any `json:"data,omitempty"` } func ok(w http.ResponseWriter, data any) { httpx.WriteJson(w, http.StatusOK, Response{Code: 0, Message: "ok", Data: data}) } func fail(w http.ResponseWriter, httpStatus int, message string) { httpx.WriteJson(w, httpStatus, Response{Code: -1, Message: message}) } func failCode(w http.ResponseWriter, httpStatus, code int, message string) { httpx.WriteJson(w, httpStatus, Response{Code: code, Message: message}) } // FailValidation 收集式校验失败(2026-10-20 报错规范):HTTP 200,code=3015, // data.errors 结构化清单;前端拦截器识别 3015 后用 ErrorListDialog 一次弹全,不用 ElMessage 单条。 func FailValidation(w http.ResponseWriter, errs []verr.FieldError) { httpx.WriteJson(w, http.StatusOK, Response{ Code: 3015, Message: fmt.Sprintf("保存失败,共 %d 项需要处理", len(errs)), Data: map[string]any{"errors": errs}, }) } // FailErr 统一错误出口:*verr.ValidationError → FailValidation 结构化;其他 error → 普通 fail(500)。 func FailErr(w http.ResponseWriter, err error) { var ve *verr.ValidationError if errors.As(err, &ve) { FailValidation(w, ve.Errors) return } fail(w, http.StatusInternalServerError, err.Error()) }