如何修改我的闭包以添加错误消息

时间:2017-05-10 13:43:18

标签: groovy

我有一些代码可以根据我的输入验证一些布尔规则。

def validate(x, rules) {
    rules.each {
        if(!it(x))
            throw new Exception("${x} is not valid! Validation failed!")
    }
}

def rule1 = { y -> y > 10 }
def rule2 = { y -> y != 72 }
def rule3 = { y -> y < 100 }

def rules = [rule1, rule2, rule3]

def a = 12
validate(a, rules)

我的每个规则都是包含布尔表达式的闭包。

我想调整我的规则以包含错误消息。然后在内部验证我希望在布尔值为false时抛出错误消息。

这样的事情:

if(!it(x))
   throw new Exception("${x} it(errorMsg)")

由于我的规则是关闭的,我不知道我该怎么做?有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

应该像使用Groovy一样简单:

def validate(x, rules) {
    rules.each {
        error = it x
        if(error)
            throw new Exception(error)
    }
}

def rule1 = { it > 10 ? false : "rule 1: '$it' is not valid" }
def rule2 = { it != 72 ? false : "rule 2: '$it' is not valid" }
def rule3 = { it < 100 ? false : "rule 3: '$it' is not valid" }

def rules = [rule1, rule2, rule3]

def a = 12
validate a, rules

这里有另一种变体:

def validate(x, rules) {
    rules.each { r, e ->
        if(!r(x))
            throw new Exception(e(x))
    }
}

def rule1 = [{ it > 10 }, { "rule 1: '$it' is not valid" }]
def rule2 = [{ it != 72 }, { "rule 2: '$it' is not valid" }]
def rule3 = [{ it < 100 }, { "rule 3: '$it' is not valid" }]

def rules = [rule1, rule2, rule3]

def a = 12
validate a, rules

答案 1 :(得分:1)

您可以尝试这种方式(每个规则是一个包含验证结束和错误消息的地图):

def validate(x, rules) {
    rules.each {
        if(!it.r(x))
            throw new Exception(it.e)
    }
}

def rule1 = [r: { it <= 10} , e:"rule 1 is not valid" ] 
def rule2 = [r: { it == 72} , e:"rule 2 is not valid" ]
def rule3 = [r: { it >= 100}, e:"rule 3 is not valid" ]

def rules = [rule1, rule2, rule3]

def a = 12
validate a, rules

答案 2 :(得分:0)

如何将规则用作地图中的键?

def validate(x, rules) {
    rules.each { rule, condition ->
        if(!condition(x))
            throw new Exception("${rule} is not valid! Validation failed!")
    }
}

def rules = [
    rule1 : { y -> y > 10 },
    rule2 : { y -> y != 72 },
    rule3 : { y -> y < 100 }
]

def a = 12
validate(a, rules)

validate 101, rules // java.lang.Exception: rule3 is not valid! Validation failed!