kratos
kratos copied to clipboard
[Question] 参数绑定,类型不一致,该如何处理?开启 validate.Validator 验证也没用
Please see the FAQ in our main README.md before submitting your issue. Please see the FAQ in our main README.md before submitting your issue.
proto文件
syntax = "proto3";
package helloworld.v1;
import "google/api/annotations.proto";
import "validate/validate.proto";
option go_package = "helloworld/api/helloworld/v1;v1";
option java_multiple_files = true;
option java_package = "dev.kratos.api.helloworld.v1";
option java_outer_classname = "HelloworldProtoV1";
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {
option (google.api.http) = {
get: "/helloworld/{name}/{age}"
};
}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1 [
(validate.rules).string = {min_len: 5}
];
uint32 age = 2 [
(validate.rules).uint32 = {gte: 18}
];
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
gomod
module helloworld
go 1.17
require (
github.com/envoyproxy/protoc-gen-validate v0.6.7
github.com/go-kratos/kratos/v2 v2.4.1
github.com/google/wire v0.5.0
google.golang.org/genproto v0.0.0-20220802133213-ce4fa296bf78
google.golang.org/grpc v1.48.0
google.golang.org/protobuf v1.28.1
)
问题
参数 age
设置为 uint32
,但是用户访问地址: http://127.0.0.1:8000/helloworld/test/txtxt
导致无法绑定参数,直接报错
{
"code": 500,
"reason": "",
"message": "parsing field \"age\": strconv.ParseUint: parsing \"txtxt\": invalid syntax",
"metadata": {
}
}
开启validate.Validator
中间件,我以为会先走 validate.Validator
,但是并不是,请问这种有啥好的处理方案???我看到 #2250 ,不知道该 issue
是否能帮到我??
bind 发生在 中间件处理之前,类型错误本身就应该直接报错
是否可以有机制接管这个错误进行自定义处理?目前是直接把错误信息直接推送前端,我想的是可以接管这个错误
我也觉得这种机制比较重要
gin 之类的也只能做具体校验吧,类型校验好像也是不可控吧
gin 之类的也只能做具体校验吧,类型校验好像也是不可控吧
gin 绑定参数错误的时候,可以接管错误的
我现在用kratos遇到的问题就是针对这种前端传入类型与我protobuf类型不匹配的时候,我这基本不能处理这种问题,而是走的默认处理方式,这种方式回暴露我们的内部信息,不符合需求
代码已提交,打完tag就能用了