【问题标题】:Making sure a var is bound in Clojure确保在 Clojure 中绑定了一个 var
【发布时间】:2015-02-17 07:31:05
【问题描述】:

在我的中间件中,我正在检查:session 的值以查看用户是否已登录。

如果设置了:session 的值,效果会很好。虽然,我不确定检查 :session 是否绑定的最佳方法。

(defn logged-in-verify
  [ring-handler]
  (fn new-ring-handler
    [request]
    ;;verify that the scrypt hash of email and timestamp matches.
    (let [session   (:session request)
          email     (:ph-auth-email session)
          token     (:ph-auth-token session)
          timestamp (:ph-auth-timestamp session)]
      (if (scryptgen/check (str email timestamp) token)
        (do 
          ;; return response from wrapped handler
          (ring-handler request))
        ;; return error response
        {:status 400, :body "Please sign in."}))))

由于我不检查 :session 是否已绑定,因此如果未设置,使用此中间件的内容将返回 NullPointerException。最好的方法是什么?

【问题讨论】:

    标签: clojure nullpointerexception ring


    【解决方案1】:

    使用when-let 或类似的if-let 来检查您是否真的有会话:

    (defn logged-in-verify
      [ring-handler]
      (fn new-ring-handler
        [request]
        ;;verify that the scrypt hash of email and timestamp matches.
        (if-let [session   (:session request)]
            (let [email     (:ph-auth-email session)
                  token     (:ph-auth-token session)
                  timestamp (:ph-auth-timestamp session)]
              (if (scryptgen/check (str email timestamp) token)
                 ;; return response from wrapped handler
                 (ring-handler request))
                 ;; return error response
                 {:status 400, :body "Please sign in."}))
            ;; do something when there is no session yet
            (generate-new-session-and-redirect))))
    

    【讨论】:

    • 我仍然得到一个空指针异常......也许我错过了一些东西......会玩弄它。
    • 啊,事实证明 :session 总是设置的,尽管首先是 {}。添加一个额外的 if-let 似乎是要走的路。谢谢
    • 那么你可以改用get-in。鉴于您的问题,您可能希望拥有类似 (if-let* [email (get-in request [:session :ph-auth-email] token (get-in request [:session :ph-auth-token] ...)if-let* 不存在的东西。参照。 a related SO question.
    【解决方案2】:

    环请求只是映射,因此您可以使用“包含?”查看它是否包含特定的键,或者“get”以获取与该键关联的值,如果该键不在地图中,则为默认值。

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 2012-10-04
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2011-12-01
      • 2014-03-21
      • 1970-01-01
      • 2014-03-11
      相关资源
      最近更新 更多