Skip to content

Instantly share code, notes, and snippets.

@NathanHowell
Created July 17, 2012 07:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NathanHowell/97540a0ae42860ef953b to your computer and use it in GitHub Desktop.
Save NathanHowell/97540a0ae42860ef953b to your computer and use it in GitHub Desktop.
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
module AlphaHeavy.Exception
( setDefaultUncaughtExceptionHandler
, lastException
, uncaughtExceptionHandler
) where
import Control.Exception (Exception(..), SomeException(..))
import Data.IORef (IORef, newIORef, writeIORef)
import Data.Typeable (Typeable)
import GHC.Conc (setUncaughtExceptionHandler)
import System.IO (hPutStrLn, stderr)
import System.IO.Unsafe (unsafePerformIO)
import System.Posix.Signals (raiseSignal, sigABRT)
import System.Posix.Syslog
-- | a dummy exception to initialize the global IORef with
data NoException = NoException deriving (Typeable)
instance Show NoException where
show _ = "<<no exception>>"
instance Exception NoException
-- | storage for the last exception
lastException :: IORef SomeException
{-# NOINLINE lastException #-}
lastException = unsafePerformIO . newIORef $ SomeException NoException
-- | when no catch frame handles an exception dump core and terminate the process
uncaughtExceptionHandler :: SomeException -> IO ()
{-# NOINLINE uncaughtExceptionHandler #-}
uncaughtExceptionHandler !e = do
writeIORef lastException e
syslog Error $ "Unhandled exception: " ++ show e
hPutStrLn stderr $ "Unhandled exception: " ++ show e
raiseSignal sigABRT
setDefaultUncaughtExceptionHandler :: IO ()
setDefaultUncaughtExceptionHandler =
setUncaughtExceptionHandler uncaughtExceptionHandler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment