:pre中有关Clojure.Spec验证的有意义的错误消息 [英] Meaningful error message for Clojure.Spec validation in :pre

查看:73
本文介绍了:pre中有关Clojure.Spec验证的有意义的错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用了最后几天来深入研究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 守卫。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆