Fork me on GitHub
#biff
<
2024-03-23
>
jamesmintram09:03:57

What's the best way to "raise" a 404 inside a request handler so that it gets picked up by the on-error handler? Should I throw an exception? or return a map? Code looks roughly like

(fn detail-view [ent-id]
(let [ent (get-from-db ent-id)]
....))
a couple of options
(fn detail-view [ent-id]
(let [ent (get-or-404 ent-id)]
...))
not sure what exception should be thrown inside of get-or-404 or
(fn detail-view [ent-id]
(if-let [ent-id (get-from-id ent-id)]
(do stuff)
{:error 404})
not sure what the map should look like when returning 404

Jacob O'Bryant00:03:52

You can return a map with :status 404, like

(defn detail-view [ent-id]
  (if-let [ent (get-from-id ent-id)]
    (do-stuff ent)
    {:status 404
     :headers {"content-type" "text/plain"}
     :body "Not found"}))

Jacob O'Bryant04:03:51

actually I'm not 100% sure that'll trigger the on-error handler--it might only get triggered by reitit E.g. if the client requests a route that doesn't even exist. either way, if you're in a situation where you're returning a :status 404 or some other error, you can just call the on-error handler directly and use that as your ring response.