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())) } // 如果原始传入的不是指针类型,需要进行深度克隆以避免修改原始数据