如何编写一个简单的错误拦截器?

时间:2013-07-22 21:21:34

标签: clojure pedestal

这是我在Pedestal上第一次尝试捕捉拦截器:

(definterceptorfn catcher []
   (interceptor
   :error (fn [context error]
           {:status 500 
            :body (->> error .toString (hash-map :error) json/write-str)
            :headers {"Content-type" "application/json"}})))

正如我可以测试的那样,通过在我的代码中添加(/ 1 0),该函数会被调用,但客户端会获得状态为200的空响应,而不是地图中的响应。我想知道为什么会这样。

我的路线变量中没有什么花哨的东西:

(defroutes routes
  [[["/api"
     ^:interceptors [(body-params/body-params) (catcher) bootstrap/html-body]
     ...

1 个答案:

答案 0 :(得分:2)

作为Tim Ewald explained,当需要上下文时,我正在返回响应图。

已修复

(definterceptorfn catcher []
   (interceptor
   :error (fn [context error]
           (assoc context :response
            {:status 500 
             :body (->> error .toString (hash-map :error) json/write-str)
             :headers {"Content-type" "application/json"}}))))