Recover in PureScript
module Main where
import Effect.Console (log)
import Effect (Effect)
-- This function throws an exception.
mayThrow :: Effect Unit
mayThrow = throwException $ error "a problem"
main :: Effect Unit
main = do
-- `try` must be used to catch exceptions.
-- When the enclosed function throws an exception,
-- the `try` will catch it and return an `Either`.
result <- try mayThrow
case result of
Left e ->
-- The Left constructor of Either contains the error
log $ "Recovered. Error:\n" <> show e
Right _ ->
-- This code will not run, because `mayThrow` throws an exception.
-- The execution of `main` stops at the point of the exception
-- and resumes in the `case` expression.
log "After mayThrow()"
PureScript makes it possible to recover from exceptions using the try
function from the Effect.Exception
module. A try
can catch an exception and return it as a value, allowing the program to continue execution instead of aborting.
An example of where this can be useful: a server wouldn’t want to crash if one of the client connections exhibits a critical error. Instead, the server would want to close that connection and continue serving other clients.
In PureScript, exception handling is done through the Either
type, where Left
represents an error and Right
represents a successful result.
To run this program, you would typically compile it with the PureScript compiler and then run it with Node.js:
$ pulp run
Recovered. Error:
Error: a problem
Note that PureScript’s exception handling is more explicit than in some other languages. You must use try
to catch exceptions, and the result is always an Either
that you must pattern match on to handle both the success and error cases.