[Haskell-cafe] converting IOException to Either in ErrorT

David Menendez dave at zednenem.com
Mon May 4 01:05:56 EDT 2009


On Sun, May 3, 2009 at 6:36 PM,  <brian at lorf.org> wrote:
> I wrote this to make it a little nicer to catch IO exceptions and
> convert them to ErrorT failure:
>
> onExceptionThrowError
>  :: (Error ce) =>
>     IO a
>  -> (String -> ce)
>  -> ErrorT ce IO a
> onExceptionThrowError a ce =
>    liftIO (try a) >>=
>      either
>        (\(e :: IOException) -> throwError (ce (show e)))
>        return
>
> So now I can do, e.g.,
> writeFile fp s `onExceptionThrowError` SpecificErrorConstructor ...
>
> It works, but seems bad. Please let me know if you see ways to improve
> it. Thanks.

What about this?

liftCatch :: (IOException -> e) -> IO a -> ErrorT e IO a
liftCatch f m = ErrorT $ liftM (either (Left . f) Right) (try m)

-- 
Dave Menendez <dave at zednenem.com>
<http://www.eyrie.org/~zednenem/>


More information about the Haskell-Cafe mailing list