       (handler request)
       (catch ExceptionInfo e
         (let [response (ex-data e)]
-          {:status  (:code response)
-           :headers {"Content-Type" "application/json"}
-           :body    {:error (:message response)}})))))
+          (json-response (:code response)
+                         (:message response)))))))
 
 (defn wrap-fallback-exception
   [handler]

(ns swarmpit.server
  (:import (clojure.lang ExceptionInfo))
  (:use [org.httpkit.server :only [run-server]])
  (:require [swarmpit.handler :refer [handler]]
            [ring.middleware.json :as ring-json]
            [cheshire.core :refer [parse-string]]))

(defn wrap-client-exception
  [handler]

      (catch Exception e
        {:status 500 :body e}))))

(defn wrap-authentication
  [handler]
  (fn [request]
    (if (secure? request)
      (let [headers (:headers request)
            token (get headers "authorization")]
        (if (some? token)
          (if true
            (handler request)
            (json-response 401 "Invalid token"))
          (json-response 400 "Missing token")))
      (handler request))))

(def app
  (-> handler
      wrap-authentication
      wrap-client-exception
      ring-json/wrap-json-response
      ring-json/wrap-json-params
