<div dir="ltr"><div>Hello,<br><br></div>I am writing a small application that uses a monad transformer stack, and I&#39;m looking for advice on the best way to handle IO errors. Ideally I&#39;d like to be able to perform an action (such as readFile &quot;file_that_does_not_exist&quot;), catch the IOError, and then convert it to a string error in MonadError. Here&#39;s an example of what I&#39;m doing now:<br>
<div><div><div><div><div><span style="font-family:courier new,monospace"><br>{-# LANGUAGE FlexibleContexts #-}<br><br>import Control.Monad.Error<br>import Control.Monad.State<br><br>import System.IO.Error (tryIOError)<br>
<br>catcher :: (MonadIO m, MonadError String m) =&gt; IO a -&gt; m a<br>catcher action = do<br>  result &lt;- liftIO $ tryIOError action<br>  case result of<br>    Left  e -&gt; throwError (show e)<br>    Right r -&gt; return r<br>
</span><br></div><div>This does work as expected, but I get the nagging feeling that I&#39;m missing an underlying pattern here. I have tried catch, catchError, and several others, but (unless I misused them) they don&#39;t actually help here. The tryIOError function from System.IO.Error is the most helpful, but I still have to manually inspect the result to throwError or return to my underlying monad.<br>
<br></div><div>Since this has come up for me a few times now, I welcome any advice or suggestions on alternative approaches or whether this functionality already exists somewhere.<br><br>Thanks!<br>Eric<br><br></div><div>
<br><br><br><br></div></div></div></div></div></div>