refactor: 改进错误处理,使用预定义错误替代硬编码字符串

- fieldx.Schema.Generate: 添加 panic 捕获机制,优雅处理 reflux.New 的异常
- fieldx.Schema.Generate: 支持 any 类型参数,增强通用性
- reflux.New: 使用预定义错误(ErrInvalidValue, ErrTargetNilPointer, NewErrUnsupportedTargetType)替代硬编码错误字符串
- 提高错误信息的一致性和可读性
This commit is contained in:
what 2025-12-26 21:15:31 +08:00
parent a6d3e34e53
commit b73099d205
2 changed files with 17 additions and 11 deletions

View File

@ -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 递归生成字段

View File

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