适配 errorx v1.2:错误值不持有 ctx,改用 errors.As + GetCode/Msg(ctx)
- response.go: errorx.As/val.Code() 换成 errors.As(errorx.ErrorInterface) 取 GetCode(),文案改用 Msg(ctx) 按请求语言渲染(errorx v1.2 起错误值只保存语言, 渲染时再传 ctx)。 - FormatMessage: langx v0.1 起未知 key 的默认码从 200 变成 -1,命中默认码时 回落到 SetDefaultSuccessCode,保持升级前 code:200 的行为。 - go.mod: github.com/yuninks/errorx v1.2.0 / github.com/yuninks/langx v0.1.0。
This commit is contained in:
+16
-4
@@ -6,6 +6,7 @@ package responsex
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/yuninks/errorx"
|
||||
@@ -58,6 +59,12 @@ func resolveSuccessMessage(ctx context.Context) string {
|
||||
// Msg格式化响应
|
||||
func FormatMessage(ctx context.Context, w http.ResponseWriter, msgKey string, format map[string]string, data interface{}, ops ...Option) {
|
||||
code, msg := langx.GetTransFormatCtx(ctx, msgKey, format)
|
||||
// langx v0.1 起「未知 key」的默认码是 -1(v0.0.x 是 200)。responsex 的成功码
|
||||
// 由 SetDefaultSuccessCode 决定,所以把默认码视为「没有业务码」,回落到它,
|
||||
// 保持与升级前一致的 code:200。
|
||||
if code == langx.GetDefaultCode() {
|
||||
code = op.defaultSuccessCode
|
||||
}
|
||||
baseOps := []Option{SetCode(code), SetMessage(msg), SetData(data)}
|
||||
baseOps = append(baseOps, ops...)
|
||||
ResponseCtx(ctx, w, baseOps...)
|
||||
@@ -85,12 +92,17 @@ func ErrorWithData(ctx context.Context, w http.ResponseWriter, err error, data i
|
||||
code := op.defaultErrorCode
|
||||
msg := "请求失败"
|
||||
if err != nil {
|
||||
if val, ok := errorx.As(err); ok {
|
||||
if langx.GetDefaultCode() != val.Code() {
|
||||
code = val.Code()
|
||||
// errorx v1.2 起错误值不再持有 context:错误常量只负责定义与构造,
|
||||
// 文案要在出口用 Msg(ctx) 按请求语言渲染,业务码用 GetCode() 取。
|
||||
var ei errorx.ErrorInterface
|
||||
if errors.As(err, &ei) {
|
||||
if bizCode := ei.GetCode(); langx.GetDefaultCode() != bizCode {
|
||||
code = bizCode
|
||||
}
|
||||
msg = ei.Msg(ctx)
|
||||
} else {
|
||||
msg = err.Error()
|
||||
}
|
||||
msg = err.Error()
|
||||
}
|
||||
baseOps := []Option{SetCode(code), SetMessage(msg), SetData(data)}
|
||||
baseOps = append(baseOps, ops...)
|
||||
|
||||
Reference in New Issue
Block a user