Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use gconv.Struct in a nested structure to obtain the original failed error after the conversion fails? #3442

Closed
shuqingzai opened this issue Apr 1, 2024 · 0 comments

Comments

@shuqingzai
Copy link

What do you want to ask

package tests

import (
	"fmt"
	"strconv"
	"testing"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
)

type Level int

const (
	LevelNormal Level = 0
	LevelGood   Level = 1
	LevelGreat  Level = 2
)

// MarshalText 实现接口: [encoding.TextMarshaler]
func (e Level) MarshalText() ([]byte, error) {
	return strconv.AppendInt([]byte{}, int64(e), 10), nil
}

// UnmarshalText 实现接口: [encoding.TextUnmarshaler]
func (e *Level) UnmarshalText(text []byte) error {
	i, err := strconv.ParseInt(string(text), 10, 32)
	if err != nil {
		return fmt.Errorf("invalid main.Level value: %s, error: %w", text, err)
	}
	*e = Level(i)
	return nil
}

type User struct {
	Name  string `json:"name" dc:"用户名称" v:"required|length:6,30" `
	Level Level  `json:"level" v:"required" dc:"等级"`
}

type Hello struct {
	Name string `json:"name" v:"required" dc:"名称"`
	User *User  `json:"user" v:"required" dc:"用户"`
}

func Test_Once(t *testing.T) {
	params := map[string]any{
		"name":  "u",
		"level": "l",
	}

	var data *User
	if err := gconv.Struct(params, &data); err != nil {
		t.Errorf("gconv.Struct failed: %+v", err)
	}
	g.Dump(data)

}

func Test_Nested(t *testing.T) {
	params := map[string]any{
		"name": "test",
		"user": map[string]any{
			"name":  "u",
			"level": "l",
		},
	}

	var data *Hello
	if err := gconv.Struct(params, &data); err != nil {
		t.Errorf("gconv.Struct failed: %+v", err)
	}
	g.Dump(data)
}

运行上诉的测试,Test_Once 可以拿到我自己设置的错误 invalid main.Level value~~~~ ,但是 Test_Nested 无法获取,只能获取 panic 的错误 gconv.Struct failed: reflect.Value.Convert: value of type map[string]interface {} cannot be converted to type tests.User 因为转换错误时,强制设置反射内容到 Hello.User 中导致 panic

@Issues-translate-bot Issues-translate-bot changed the title 如何在 嵌套结构体中使用 gconv.Struct 转换失败后获取原始失败的 error ? How to use gconv.Struct in a nested structure to obtain the original failed error after the conversion fails? Apr 1, 2024
@shuqingzai shuqingzai reopened this Apr 1, 2024
@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale May 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant