macchiato-framework / macchiato-core

Ring style HTTP server abstraction for Node.js
MIT License
377 stars 35 forks source link

Possibility to write default error handler if something goes wrong #40

Open nenadalm opened 4 years ago

nenadalm commented 4 years ago

Hi. Instead of using callbacks in handlers/middlewares I prefer to use promises.

The reason is that if I (or somebody else) forget to handle some error - I can still set some handling and return 500 instead of waiting for timeout.

Currently I am using this middleware to take care of unexpected errors in my handlers:

(ns app.routes.middleware.rejection
  (:require
   [taoensso.timbre :as timbre]))

(defn wrap-rejection
  "Middleware returns `500` if handler returned rejected promise and logs the error."
  [handler]
  (fn [req res raise]
    (let [result (handler req res raise)]
      (when (instance? js/Promise result)
        (.catch result
                (fn [e]
                  (timbre/error e "Rejection middleware caught error")
                  (res {:status 500})))))))

Would you accept possible prs that would convert callbacks into promises like https://github.com/macchiato-framework/macchiato-core/blob/f21bddc621745696b85e5fa97870f6fe913fcf1a/src/macchiato/middleware/restful_format.cljs#L129?

yogthos commented 4 years ago

Hi, yeah I agree that promises are easier to work with and a PR would be very welcome.