确保在Clojure中绑定var

sov*_*ova 3 clojure nullpointerexception ring

在我的中间件中,我正在检查: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."}))))
Run Code Online (Sandbox Code Playgroud)

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

sch*_*eho 5

使用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))))
Run Code Online (Sandbox Code Playgroud)

  • 然后你可以选择使用`get-in`.鉴于你的问题,你可能希望有类似`(if-let*[email(get-in request [:session:ph-auth-email]令牌)(get-in request [:session:ph-auth-]令牌......)`但是`if-let*`不存在.参见[相关的SO问题](/sf/ask/817328431/如果,让支持 - 多绑定按默认值). (3认同)