:pre中有关Clojure.Spec验证的有意义的错误消息 [英] Meaningful error message for Clojure.Spec validation in :pre
问题描述
我用了最后几天来深入研究Clojure和ClojureScript中的 clojure.spec 。
I used the last days to dig deeper into clojure.spec in Clojure and ClojureScript.
直到现在我发现它最有用,在依赖某些格式数据的公共函数中,在:pre
和:post
中将规范用作防护。 / p>
Until now I find it most useful, to use specs as guards in :pre
and :post
in public functions that rely on data in a certain format.
(defn person-name [person]
{:pre [(s/valid? ::person person)]
:post [(s/valid? string? %)]}
(str (::first-name person) " " (::last-name person)))
该方法的问题是,我得到了 java.lang.AssertionError:Assert failed:(( s / valid?:: person person)
,而没有任何有关完全不符合规范的信息。
The issue with that approach is, that I get a java.lang.AssertionError: Assert failed: (s/valid? ::person person)
without any information about what exactly did not met the specification.
有人在:pre
中找到了一个如何获取更好的错误消息的方法 :后卫
警卫?
Has anyone an idea how to get a better error message in :pre
or :post
guards?
我知道符合 c并且
解释*
,但这对那些:pre
或:post $而言无济于事c $ c>守卫。
I know about conform
and explain*
, but that does not help in those :pre
or :post
guards.
推荐答案
在较新的Alpha中,现在有 s / assert
可用于断言输入或返回值与规范匹配。如果有效,则返回原始值。如果无效,则将引发断言错误以及解释结果。断言可以打开或关闭,甚至可以选择从整个编译代码中完全省略,以产生0的生产影响。
In newer alphas, there is now s/assert
which can be used to assert that an input or return value matches a spec. If valid, the original value is returned. If invalid, an assertion error is thrown with the explain result. Assertions can be turned on or off and can even optionally be omitted from the compiled code entirely to have 0 production impact.
(s/def ::first-name string?)
(s/def ::last-name string?)
(s/def ::person (s/keys :req [::first-name ::last-name]))
(defn person-name [person]
(s/assert ::person person)
(s/assert string? (str (::first-name person) " " (::last-name person))))
(s/check-asserts true)
(person-name 10)
=> CompilerException clojure.lang.ExceptionInfo: Spec assertion failed
val: 10 fails predicate: map?
:clojure.spec/failure :assertion-failed
#:clojure.spec{:problems [{:path [], :pred map?, :val 10, :via [], :in []}], :failure :assertion-failed}
这篇关于:pre中有关Clojure.Spec验证的有意义的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!