4 ms·
So how are errors handled?
by jbooth 12y ago
So how are errors handled?
- spion 12y agoYou have the option of two monads, Maybe and Either. Usually errors are handled with the Either monad. An operation may either return a result or an error. Together with do syntax the Either monad gives you multiple choices in handling errors. You can handle every single error explicitly (as in Go) using pattern matching eitherResultOrError = operation1 arg case eitherResultOrError of Left error -> handle error Right result -> handle' result Its also possible to chain multiple operations then check the error later. If an error occurs, the next operations in the chain will not execute. let eitherResultOrError = do x <- operation1 arg y <- operation2 x + 1 z <- operation3 x y case eitherResultOrError of Left error -> handle error Right result -> handle' result Or simply use `orElse` to return a default value in case of errors. For IO operations and other monadic actions, its best to use EitherT, ErrorT or MaybeT, which are monads that can add error handling to any other monad. To understand how these work, its probably best to implement MaybeT. Basically, they add another wrapper to other monads to redefine what the bind operator (`>>=`) does