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
如果它未设置.最好的方法是什么?
使用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)