From b73099d2058c3fdfd27082f5ae21a3fc0ffd7a21 Mon Sep 17 00:00:00 2001 From: what Date: Fri, 26 Dec 2025 21:15:31 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E6=94=B9=E8=BF=9B=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E5=A4=84=E7=90=86,=E4=BD=BF=E7=94=A8=E9=A2=84?= =?UTF-8?q?=E5=AE=9A=E4=B9=89=E9=94=99=E8=AF=AF=E6=9B=BF=E4=BB=A3=E7=A1=AC?= =?UTF-8?q?=E7=BC=96=E7=A0=81=E5=AD=97=E7=AC=A6=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - fieldx.Schema.Generate: 添加 panic 捕获机制,优雅处理 reflux.New 的异常 - fieldx.Schema.Generate: 支持 any 类型参数,增强通用性 - reflux.New: 使用预定义错误(ErrInvalidValue, ErrTargetNilPointer, NewErrUnsupportedTargetType)替代硬编码错误字符串 - 提高错误信息的一致性和可读性 --- fieldx/schema.go | 22 ++++++++++++++-------- reflux.go | 6 +++--- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/fieldx/schema.go b/fieldx/schema.go index 4351fee..a20cb1f 100644 --- a/fieldx/schema.go +++ b/fieldx/schema.go @@ -38,17 +38,23 @@ type Schema map[string]Field // Generate 根据 Schema 生成对象 // source: 源数据对象,用于 FieldTypeField 类型获取字段值 -// 返回生成的 map[string]any 对象 -func (s Schema) Generate(source map[string]any) (map[string]any, error) { +// 返回生成的 map[string]any 对象,如果 source 无效或处理失败则返回错误 +func (s Schema) Generate(source any) (result map[string]any, err error) { + // 捕获 reflux.New 可能产生的 panic + defer func() { + if r := recover(); r != nil { + result = nil + err = fmt.Errorf("failed to wrap source data: %v", r) + } + }() + // 使用 reflux 包装源数据,提供统一的访问接口 rfx := reflux.New(source) - result := make(map[string]any) - err := s.generateFields(rfx, result) - if err != nil { - return nil, err - } - return result, nil + result = make(map[string]any) + err = s.generateFields(rfx, result) + + return result, err } // generateFields 递归生成字段 diff --git a/reflux.go b/reflux.go index b587443..5b1c211 100644 --- a/reflux.go +++ b/reflux.go @@ -65,14 +65,14 @@ func New(v any) R { } if !rv.IsValid() { - panic("rfx: invalid value") + panic(ErrInvalidValue) } // 递归解引用指针和接口,直到获取实际的值类型 actualValue := rv for actualValue.Kind() == reflect.Ptr || actualValue.Kind() == reflect.Interface { if actualValue.IsNil() { - panic("rfx: cannot use nil pointer or nil interface") + panic(ErrTargetNilPointer) } actualValue = actualValue.Elem() // 如果解引用后的类型是指针,标记为指针模式 @@ -93,7 +93,7 @@ func New(v any) R { reflect.Float64: // 支持的类型 default: - panic("rfx: unsupported type, only map, struct, slice, and array are allowed") + panic(NewErrUnsupportedTargetType(actualValue.Kind())) } // 如果原始传入的不是指针类型,需要进行深度克隆以避免修改原始数据