golang error处理之多error聚合

下面这段代码取自于云原生开源项目karmada,我们可以借鉴以下它的检查参数中处理error的方法。

// Validate checks Options and return a slice of found errs.
func (o *Options) Validate() field.ErrorList {
    errs := field.ErrorList{}
    newPath := field.NewPath("Options")
​
    skippedResourceConfig := util.NewSkippedResourceConfig()
    if err := skippedResourceConfig.Parse(o.SkippedPropagatingAPIs); err != nil {
        errs = append(errs, field.Invalid(newPath.Child("SkippedPropagatingAPIs"), o.SkippedPropagatingAPIs, "Invalid API string"))
    }
    if o.SecurePort < 0 || o.SecurePort > 65535 {
        errs = append(errs, field.Invalid(newPath.Child("SecurePort"), o.SecurePort, "must be between 0 and 65535 inclusive"))
    }
    if o.ClusterStatusUpdateFrequency.Duration <= 0 {
        errs = append(errs, field.Invalid(newPath.Child("ClusterStatusUpdateFrequency"), o.ClusterStatusUpdateFrequency, "must be greater than 0"))
    }
    if o.ClusterLeaseDuration.Duration <= 0 {
        errs = append(errs, field.Invalid(newPath.Child("ClusterLeaseDuration"), o.ClusterLeaseDuration, "must be greater than 0"))
    }
    if o.ClusterMonitorPeriod.Duration <= 0 {
        errs = append(errs, field.Invalid(newPath.Child("ClusterMonitorPeriod"), o.ClusterMonitorPeriod, "must be greater than 0"))
    }
    if o.ClusterMonitorGracePeriod.Duration <= 0 {
        errs = append(errs, field.Invalid(newPath.Child("ClusterMonitorGracePeriod"), o.ClusterMonitorGracePeriod, "must be greater than 0"))
    }
    if o.ClusterStartupGracePeriod.Duration <= 0 {
        errs = append(errs, field.Invalid(newPath.Child("ClusterStartupGracePeriod"), o.ClusterStartupGracePeriod, "must be greater than 0"))
    }
​
    return errs
}
​

因为要检查的参数有多个,所以在检查的过程中遇到不合理的配置参数不马上返回错误,而将错误一一追加到一个错误列表里面。

// ToAggregate converts the ErrorList into an errors.Aggregate.
func (list ErrorList) ToAggregate() utilerrors.Aggregate {
    if len(list) == 0 {
        return nil
    }
    errs := make([]error, 0, len(list))
    errorMsgs := sets.NewString()
    for _, err := range list {
        msg := fmt.Sprintf("%v", err)
        if errorMsgs.Has(msg) {
            continue
        }
        errorMsgs.Insert(msg)
        errs = append(errs, err)
    }
    return utilerrors.NewAggregate(errs)
}

ToAggregate这个则是位于k8s.io/kubernetes/staging/src/k8s.io/apimachinery/pkg/util/validation/field/errors.go里封装的一个方法了。

你可能感兴趣的:(golang,kubernetes,golang,开发语言,后端)