擅长:python、mysql、java
<p>如果您试图捕获错误并仅在错误发生时继续执行您的函数,该怎么办?例如,以这种方式:</p>
<pre><code>class MyValidator(Validator):
def _check_with_sum_eq_one(self, field, value):
""" Checks whether value is a list and its sum equals 1.0. """
if isinstance(value, list) and sum(value) != 1.0:
self._error(str(value), f"Sum of '{field}' must exactly equal 1")
schema2 = {
"key1": {
"type": ["list", "float"],
"min": 1,
"max": 1,
"schema": {"type": "float", "min": 0, "max": 1},
"check_with": "sum_eq_one",
}
}
v = MyValidator(schema2)
document1 = {"key1": 1}
document2 = {"key1": 5}
document3 = {"key1": "5"}
document4 = {"key1": [0.3, 0.5]} # error
document5 = {"key1": ["0.5", 0.3]} # error
#document6 = {"key1": [0.5, 0.5]} # error
assert v.validate(document1)
assert not v.validate(document2)
assert not v.validate(document3)
assert v.validate(document4)
assert not v.validate(document5)
</code></pre>