[Haskell-beginners] exception, not in IO

Ertugrul Söylemez es at ertes.de
Sun Jul 14 15:06:32 CEST 2013


"Kees Bleijenberg" <k.bleijenberg at lijbrandt.nl> wrote:

> But sometimes the jsonString is not valid (misformed or wrong fields).
> decodeJSON then throws a exception.  I want to
>
> catch that exection and transform the result to something like ("" ,
> theErrorMsg). Unfortunately all catch functions want IO parameters.
>
> What can I do?

IO is just one of the many monads with exception support.  For your
case, since JSON parsing is a pure process, you would want to use a pure
exception monad like `Maybe` or `Either MyError`:

    data MyError
        = InvalidDateField
        | {- ... -}
        | UnknownError

There is nothing wrong with using regular exception types, if you wish,
in which case you might use `Either SomeException`.  Then separate
concerns:

    decode :: String -> Either MyError Glass
    encode :: Glass -> String

Finally the conversion function is as simple as:

    convert :: String -> Either MyError String
    convert = fmap encode . decode

If `encode` can fail as well and exceptions are regular Haskell
exceptions:

    import Control.Exception
    import Control.Monad

    decode :: String -> Either SomeException Glass
    encode :: Glass -> Either SomeException String

    convert :: String -> Either SomeException String
    convert = encode <=< decode

I hope this helps.


Greets,
Ertugrul

-- 
Not to be or to be and (not to be or to be and (not to be or to be and
(not to be or to be and ... that is the list monad.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20130714/a405caa4/attachment.pgp>


More information about the Beginners mailing list