Search code examples
clojurepedestal

How to write a simple error interceptor?


Here's my first attempt of a catcher interceptor on Pedestal:

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

As I could test, by adding (/ 1 0) to my code, the function does get called, but the client gets an empty response with status 200, instead of the response in the map. I wonder why it is so.

There is nothing fancy in my routes variable:

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

Solution

  • As Tim Ewald explained, I was returning a response map when a context was needed.

    Fixed with

    (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"}}))))