-- | Stolen from rack: catches all exceptions raised from the app it wraps.

module Hack.Contrib.Middleware.ShowExceptions (show_exceptions) where

import Hack
import Hack.Contrib.Middleware.Hub

import MPSUTF8
import Prelude hiding ((.), (^), (>), log)

import Data.Maybe
import Data.Default

import System.IO  
import System.IO.Error


program :: String
program = "ShowExceptions"

show_exceptions :: Maybe (String -> IO ()) -> Middleware
show_exceptions stream app = \env -> do
  let my_stream = stream.fromMaybe (env.hack_errors)
  let log = simple_logger my_stream program
  
  app env `catch` (handler log)

  where
    handler :: Logger -> IOError -> IO Response
    handler log e = do
      let message = e.show
      Error. log message
      return $ def { status = 500, body = message }