|
| 1 | +This is a cookbook for the usage of `safe-exceptions`. You should |
| 2 | +start off by |
| 3 | +[reading the README](https://github.com/fpco/safe-exceptions#readme), |
| 4 | +or at least |
| 5 | +[the quickstart section](https://github.com/fpco/safe-exceptions#quickstart). |
| 6 | + |
| 7 | +_Request to readers_: if there are specific workflows that you're |
| 8 | +unsure of how to accomplish with this library, please ask so we can |
| 9 | +add them here. Issues and pull requests very much welcome! |
| 10 | + |
| 11 | +## User-defined async exceptions |
| 12 | + |
| 13 | +In order to define an async exception, you must leverage the |
| 14 | +extensible exception machinery, as demonstrated below. Try running the |
| 15 | +program, and then comment out the implementation of `toException` and |
| 16 | +`fromException` to see the difference in behavior. |
| 17 | + |
| 18 | +```haskell |
| 19 | +#!/usr/bin/env stack |
| 20 | +-- stack --resolver lts-6.4 runghc --package safe-exceptions-0.1.0.0 |
| 21 | +import Control.Concurrent (forkIO, newEmptyMVar, putMVar, takeMVar, |
| 22 | + threadDelay) |
| 23 | +import Control.Exception.Safe |
| 24 | +import Data.Typeable (Typeable, cast) |
| 25 | + |
| 26 | +data MyAsyncException = MyAsyncException |
| 27 | + deriving (Show, Typeable) |
| 28 | + |
| 29 | +instance Exception MyAsyncException where |
| 30 | + toException = toException . SomeAsyncException |
| 31 | + fromException se = do |
| 32 | + SomeAsyncException e <- fromException se |
| 33 | + cast e |
| 34 | + |
| 35 | +main :: IO () |
| 36 | +main = do |
| 37 | + baton <- newEmptyMVar -- give the handler a chance to run |
| 38 | + tid <- forkIO $ threadDelay maxBound |
| 39 | + `withException` |
| 40 | + (\e -> print ("Inside withException", e :: MyAsyncException)) |
| 41 | + `finally` putMVar baton () |
| 42 | + throwTo tid MyAsyncException |
| 43 | + takeMVar baton |
| 44 | + putStrLn "Done!" |
| 45 | +``` |
| 46 | + |
| 47 | +The reason the `Inside withException` message isn't printed without |
| 48 | +the implementation of `toException` and `fromException` given above is |
| 49 | +that `throwTo` wraps `MyAsyncException` inside a different async |
| 50 | +exception type, which foils the exception handler from firing. |
| 51 | + |
| 52 | +*NOTE*: The above code is _not_ recommended concurrency code. If you |
| 53 | +have to do something like this, _please use the async package_. |
0 commit comments