驗證器結構type RegisterValidator struct { Name string `form:"name" json:"name" binding:"required,min=4,max=50"` Email string `form:"email" json:"email" binding:"required,email,min=4,max=50"` Password string `form:"password" json:"password" binding:"required,min=8,max=50"` MobileCountryCode int `form:"mobile_country_code" json:"mobile_country_code" binding:"required,gte=2,lt=5"` Mobile int `form:"mobile" json:"mobile" binding:"required,gte=5,lt=15"` UserModel users.User `json:"-"`}設置自定義錯誤的格式,如下所示:type CustomError struct { Errors map[string]interface{} `json:"errors"`}func NewValidatorError(err error) CustomError { res := CustomError{} res.Errors = make(map[string]interface{}) errs := err.(validator.ValidationErrors) for _, v := range errs { param := v.Param() field := v.Field() tag := v.Tag() if param != "" { res.Errors[field] = fmt.Sprintf("{%v: %v}", tag, param) } else { res.Errors[field] = fmt.Sprintf("{key: %v}", tag) } } return res}當發送的數據是{ "email": "[email protected]", "name": "John Doe", "mobile_country_code": 1, "mobile": 1234567}但發送無效類型{ "email": "[email protected]", "name": "John Doe", "mobile_country_code": "1", "mobile": 1234567}拋出錯誤interface conversion: error is *json.UnmarshalTypeError, not validator.ValidationErrors這個問題與此問題有關:如何斷言錯誤類型 json。當被杜松子酒c.BindJSON捕獲時,取消消息打印錯誤,但是答案沒有意義。
2 回答

慕桂英3389331
TA貢獻2036條經驗 獲得超8個贊
如異常所示,以下行類型轉換失敗
errs := err.(validator.ValidationErrors)
不同類型的錯誤必須傳遞到不是驗證器的函數中。驗證錯誤。
因此,請確保其他錯誤不會傳遞到 .或者做一個更安全的類型檢查,比如:NewValidatorError
errs, ok := err.(validator.ValidationErrors)
if !ok {
// handles other err type
}

米脂
TA貢獻1836條經驗 獲得超3個贊
我添加了對取消封版類型錯誤的檢查,如下所示:
if reflect.TypeOf(err).Elem().String() == "json.UnmarshalTypeError" {
errs := err.(*json.UnmarshalTypeError)
res.Errors[errs.Field] = fmt.Sprintf("{key: %v}", errs.Error())
return res
}
errs := err.(validator.ValidationErrors)
我猜當json是類型提示時,戈蘭是嚴格的。它必須是確切的類型,否則它將引發錯誤。UnmarshalTypeError
- 2 回答
- 0 關注
- 138 瀏覽
添加回答
舉報
0/150
提交
取消