【问题标题】:Interface conversion: interface {} is nil, not validator.ValidationErrors接口转换:interface {} 为 nil,不是 validator.ValidationErrors
【发布时间】:2020-10-31 23:30:00
【问题描述】:

我正在尝试创建一个 CRUD 并使用名为 [validator][1] 的 Go 库验证我的请求正文

验证码示例:

func (v *Validation) Validate(i interface{}) ValidationErrors {
    errs := v.validate.Struct(i).(validator.ValidationErrors) // panic originates here

    if len(errs) == 0 {
        return nil
    }

    var returnErrs []ValidationError
    for _, err := range errs {
        // cast the FieldError into our ValidationError and append to the slice
        ve := ValidationError{err.(validator.FieldError)}
        returnErrs = append(returnErrs, ve)
    }

    return returnErrs
}

上述验证器适用于无效请求正文,例如无效 ID。

但是对于一个有效的身体,它会引发恐慌

堆栈跟踪:

products-api 2020/07/12 15:15:11 http: panic serving 127.0.0.1:33288: interface conversion: error is nil, not validator.ValidationErrors
goroutine 21 [running]:
net/http.(*conn).serve.func1(0xc0003b6140)
        /usr/local/go/src/net/http/server.go:1772 +0x139
panic(0x93d6c0, 0xc0003845d0)
        /usr/local/go/src/runtime/panic.go:973 +0x3e3
github.com/AymanArif/golang-microservices/data.(*Validation).Validate(0xc0005a8108, 0x8f3480, 0xc0005aa2c0, 0x0, 0x0, 0x203000)
        /home/ayman/Desktop/golang-microservices/data/validation.go:70 +0x211

interface conversion: interface conversion: error is nil, not validator.ValidationErrors

创建 REST 逻辑:

func (p *Products) Create(rw http.ResponseWriter, r *http.Request) {
    prod := r.Context().Value(KeyProduct{}).(data.Product) // Panic originate here. Check below for struct definiton

    p.l.Printf("[DEBUG] Inserting product: %#v\n", prod)
    data.AddProduct(prod)
}

// data.Product
type Product struct {

    ID int `json:"id"` // Unique identifier for the product

    Name string `json:"name" validate:"required"`

    Description string `json:"description"`

    SKU string `json:"sku" validate:"sku"`
}

如何对正确的请求进行错误处理? [1]:https://github.com/go-playground/validator

【问题讨论】:

    标签: validation go types type-conversion


    【解决方案1】:

    如果您将 Validate 函数重新编写成这样的东西,它应该可以工作。类型断言需要检查 errs & err

    func (v *Validation) Validate(i interface{}) ValidationErrors {
    var returnErrs []ValidationError
    
    if errs, ok := v.validate.Struct(i).(validator.ValidationErrors); ok {
    
        if errs != nil {
            for _, err := range errs {
                if fe, ok := err.(validator.FieldError); ok {
                    ve := ValidationError{fe}
                    returnErrs = append(returnErrs, ve)
                }
            }
        }
    }
    
    return returnErrs
    

    }

    【讨论】:

      【解决方案2】:

      你得到的错误是雄辩的:

      interface conversion: interface {} is *data.Product, not data.Product

      r.Context().Value(KeyProduct{}) 行返回一个接口类型interface{},错误告诉你,它持有一个具体类型为*data.Product 的值(指针 指向data.Product

      相反,您尝试将其转换为data.Product,而不检查转换是否有效。

      将行替换为:

      prod := r.Context().Value(KeyProduct{}).(*data.Product)
      

      您可能想阅读有关 type assertions 的 Go Tour。


      更新后,你现在遇到的错误还是同类型的问题:

      interface conversion: error is nil, not validator.ValidationErrors

      err 实际上是nil 时,您正在尝试使用表达式err.(validator.FieldError)err 转换为validator.FieldError

      之前的检查len(errs) == 0 只是验证errs 的长度不为零,但切片可能是非零长度并且包含nil 值。

      您可以改为测试类型断言:

      if fe, ok := err.(validator.FieldError); ok {
          ve := ValidationError{fe}
          returnErrs = append(returnErrs, ve)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        • 2020-01-06
        • 2022-01-24
        • 2015-07-21
        • 2018-08-10
        • 1970-01-01
        • 2022-08-18
        相关资源
        最近更新 更多