Skip to content

Commit cee1a6d

Browse files
Fix #8 unhandled exception when parsing malformed body
1 parent 52cd93c commit cee1a6d

3 files changed

Lines changed: 14 additions & 1 deletion

File tree

src/duct/handler/static.clj

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@
4949
(defmethod ig/init-key ::bad-request [_ response]
5050
(make-handler (assoc response :status 400)))
5151

52+
(defmethod ig/init-key ::bad-request-malformed [_ response]
53+
(let [handler (make-handler (assoc response :status 400))]
54+
(fn [_ _ request]
55+
(handler request))))
56+
5257
(defmethod ig/init-key ::not-found [_ response]
5358
(make-handler (assoc response :status 404)))
5459

src/duct/middleware/web.clj

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,4 +124,8 @@
124124
b))
125125

126126
(defmethod ig/init-key ::format [_ options]
127-
#(mm/wrap-format % (deep-merge mc/default-options options)))
127+
(let [malformed-handler (or (:malformed-handler options)
128+
(ig/ref :duct.handler.static/bad-request-malformed))]
129+
#(mm/wrap-exception
130+
(mm/wrap-format % (deep-merge mc/default-options options))
131+
malformed-handler)))

src/duct/module/web.clj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@
7070

7171
(def ^:private base-config
7272
{:duct.handler.static/bad-request (plaintext-response "Bad Request")
73+
:duct.handler.static/bad-request-malformed (plaintext-response "Bad Request Malformed")
7374
:duct.handler.static/not-found (plaintext-response "Not Found")
7475
:duct.handler.static/method-not-allowed (plaintext-response "Method Not Allowed")
7576
:duct.handler.static/internal-server-error (plaintext-response "Internal Server Error")
@@ -80,6 +81,8 @@
8081

8182
(def ^:private api-config
8283
{:duct.handler.static/bad-request {:body ^:displace {:error :bad-request}}
84+
:duct.handler.static/bad-request-malformed {:body "{\"error\": \"Malformed request body\"}"
85+
:headers {"Content-Type" "application/json"}}
8386
:duct.handler.static/not-found {:body ^:displace {:error :not-found}}
8487
:duct.handler.static/method-not-allowed {:body ^:displace {:error :method-not-allowed}}
8588
:duct.handler.static/internal-server-error
@@ -113,6 +116,7 @@
113116

114117
(defn- site-config [project-ns]
115118
{:duct.handler.static/bad-request (html-response error-400)
119+
:duct.handler.static/bad-request-malformed (html-response error-400)
116120
:duct.handler.static/not-found (html-response error-404)
117121
:duct.handler.static/method-not-allowed (html-response error-405)
118122
:duct.handler.static/internal-server-error (html-response error-500)

0 commit comments

Comments
 (0)