haskell-error-handling
Error handling patterns for pragmatic Haskell. Use when choosing between Maybe, Either, exceptions, or ExceptT; when handling resources; or when designing error types.
Unsigned, install at your own risk
UnverifiedThis skill has no cryptographic signature attached. We can't verify the contents match what the publisher intended.
Install this skill
No account required. Pick your tool, or use the command that detects it for you.
Run in your terminal. It detects your AI tool.
npx @skills-hub-ai/cli install pragmatic-haskell-haskell-error-handlingManual setup by platform
Claude Code
~/.claude/skills/pragmatic-haskell-haskell-error-handling/SKILL.md
Instructions
Error Handling
The Decision Tree
Choose the right mechanism based on what the caller needs to know and do.
Is the value optional with no error information needed?
YES → Maybe
Is the error expected and recoverable, and does the caller need error context?
YES → Either e a (in the return type, not ExceptT)
Is the error unexpected or at an IO boundary (network, database, file system)?
YES → throwIO / catch
Is threading Either through the return type genuinely painful across many
IO-bound functions?
MAYBE → ExceptT (document why Either is insufficient)
Maybe
Use Maybe for values that may be absent with no useful error context.
-- Right: absence is the only failure mode, no detail needed
lookupUser :: Map UserId User -> UserId -> Maybe User
lookupUser m uid = Map.lookup uid m
-- Wrong: the caller cannot tell WHY it failed
parseConfig :: Text -> Maybe Config
parseConfig t = ... -- caller gets Nothing but no parse error
When the caller needs to know why something is absent, use Either.
Either
Use Either e a for expected, recoverable errors where the caller needs
context. Put it directly in the return type — do not reach for ExceptT
first.
data ConfigError
= MissingKey !Text
| InvalidValue !Text !Text -- key, value
deriving stock (Eq, Show)
parseConfig :: Map Text Text -> Either ConfigError Config
parseConfig m = do
host <- note (MissingKey "host") (Map.lookup "host" m)
port <- note (MissingKey "port") (Map.lookup "port" m)
portInt <- note (InvalidValue "port" port)
(readMaybe (Text.unpack port))
pure Config { configHost = host, configPort = portInt }
where
note e = maybe (Left e) Right
Either composes well with do-notation via the Monad instance, and
works naturally with mapM, traverse, and sequence.
throwIO and catch
Use throwIO for unexpected errors at IO boundaries. These are errors the
caller typically cannot recover from programmatically — database unreachable,
file system full, network timeout.
-- Define a domain exception type
data DatabaseError
= ConnectionFailed !Text
| QueryFailed !Text !Text -- query, error message
deriving stock (Show)
deriving anyclass (Exception)
-- Throw at the boundary
fetchUserFromDb :: Pool Connection -> UserId -> IO User
fetchUserFromDb pool uid = do
result <- withResource pool $ \conn ->
query conn "SELECT * FROM users WHERE id = ?" (Only (unUserId uid))
case result of
[] -> throwIO (QueryFailed "fetchUser" "no rows returned")
(u:_) -> pure u
-- Catch at the appropriate boundary (usually the top level or a retry handler)
runWithRetry :: IO a -> IO a
runWithRetry action =
action `catch` \(e :: DatabaseError) -> do
logError ("Database error: " <> Text.pack (show e))
threadDelay 1_000_000
action
Always catch specific exception types, never bare SomeException unless
you are at a top-level boundary and re-throwing or logging.
Validation Accumulation
do-notation on Either short-circuits: the first Left stops evaluation
and subsequent steps are skipped. This is usually what you want (e.g. parsing
a config field — if the field is missing the rest is meaningless).
For cases where you need all errors at once (form validation, batch
processing), do not use Either with do. Instead, collect errors manually:
-- Accumulate all errors into a list — do not use do-notation here
validateRequest :: Request -> Either [ValidationError] Request
validateRequest req =
case concat [validateName (reqName req), validateEmail (reqEmail req)] of
[] -> Right req
errs -> Left errs
For more complex accumulation, the validation package provides a
Validation type that uses Applicative to accumulate errors:
import Validation (Validation (..), failure)
validateName :: Text -> Validation [ValidationError] Text
validateEmail :: Text -> Validation [ValidationError] Text
validateRequest :: Request -> Validation [ValidationError] Request
validateRequest req =
Request
<$> validateName (reqName req)
<*> validateEmail (reqEmail req)
-- All errors are collected, not just the first
Rule: use Either with do for sequential operations where early exit
is correct. Use manual error accumulation or Validation when the caller
needs to see all failures simultaneously.
ExceptT
Use ExceptT only when:
- You are making many IO-bound calls that each return
Either, and the
threading is genuinely painful. - You document in a comment why
Eitherin the return type is insufficient.
-- Document why ExceptT is justified here:
-- This function makes 6 sequential IO calls each of which can fail with
-- ApiError. Threading Either through all of them produces deeply nested
-- case expressions. ExceptT flattens this naturally.
createPayment
:: Env
-> PaymentRequest
-> ExceptT ApiError IO PaymentId
createPayment env req = do
user <- ExceptT $ fetchUser env (reqUserId req)
account <- ExceptT $ fetchAccount env (reqAccountId req)
_ <- ExceptT $ validateBalance account (reqAmount req)
txId <- ExceptT $ initiateTransfer env account (reqAmount req)
_ <- ExceptT $ sendConfirmation env user txId
pure (paymentId txId)
Keep ExceptT at the function level; do not stack it in a persistent
transformer type unless the whole application is structured around it.
Resource Safety
Every resource acquisition must have a guaranteed cleanup path. This is
non-negotiable.
Use bracket for acquire/use/release patterns:
withDbConnection :: Pool Connection -> (Connection -> IO a) -> IO a
withDbConnection pool action =
bracket
(takeResource pool) -- acquire
(releaseResource pool) -- always runs, even on exception
action
-- Or the higher-level pool version:
withDbConnection' :: Pool Connection -> (Connection -> IO a) -> IO a
withDbConnection' = withResource
Use finally for cleanup that runs regardless of outcome:
withTempFile :: (FilePath -> IO a) -> IO a
withTempFile action = do
path <- createTempFile "/tmp" "myapp"
action path `finally` removeFile path
Never acquire a resource and release it manually without bracket. Exceptions
between acquisition and the manual release will leak the resource.
Application-Wide Exception Type
Define one exception type per application or service and use it consistently:
data AppError
= NotFound !Text -- ^ Resource type and identifier
| Unauthorised !Text -- ^ What was attempted
| ValidationFailed ![Text] -- ^ List of validation errors
| InternalError !Text -- ^ Unexpected internal error
deriving stock (Show)
instance Exception AppError
-- Convenience throwers
throwNotFound :: Text -> IO a
throwNotFound msg = throwIO (NotFound msg)
throwValidation :: [Text] -> IO a
throwValidation errs = throwIO (ValidationFailed errs)
HasCallStack on Impossible Paths
When error is used on a code path that is genuinely impossible, add
HasCallStack to the enclosing function and explain why:
-- | Select a random element from a non-empty list.
-- The list is guaranteed non-empty by the NonEmpty type,
-- so the partial pattern below is unreachable.
randomElement :: HasCallStack => NonEmpty a -> IO a
randomElement (x :| xs) = do
idx <- randomRIO (0, length xs)
pure $ case idx of
0 -> x
n -> xs !! (n - 1)
-- Note: n is in [1..length xs] by construction, so xs !! (n-1)
-- is always in bounds. The partial (!!) is unreachable.
MonadUnliftIO
When you need to use bracket, catch, or other IO exception operations
inside a transformer stack (e.g. ReaderT Env IO), prefer MonadUnliftIO
from the unliftio package over lifting IO operations manually.
import UnliftIO (MonadUnliftIO, bracket, catch, withRunInIO)
-- Works inside ReaderT Env IO without manual liftIO + unlift ceremony
withDbConnection
:: MonadUnliftIO m
=> Pool Connection
-> (Connection -> m a)
-> m a
withDbConnection pool action =
bracket
(liftIO (takeResource pool))
(liftIO . releaseResource pool)
action
Use liftIO when you only need to lift a single IO action. Use
MonadUnliftIO when you need to pass a callback back into IO (e.g.
bracket, catch, withAsync). This correctly handles the
"wrapping and unwrapping" of the transformer context.
See references/error-handling-examples.md for complete worked examples.
Security
Reviews (0)
More from Pragmatic Haskell
View source →More Build skills
Browse category →Frequently asked questions about haskell-error-handling
What does the haskell-error-handling skill do?
Error handling patterns for pragmatic Haskell. Use when choosing between Maybe, Either, exceptions, or ExceptT; when handling resources; or when designing error types. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.
How do I install the haskell-error-handling skill?
Run `npx @skills-hub-ai/cli install pragmatic-haskell-haskell-error-handling` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/pragmatic-haskell-haskell-error-handling/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.
Which AI tools does haskell-error-handling work with?
haskell-error-handling runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.
Is the haskell-error-handling skill free?
Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.
How do I use haskell-error-handling after installing it?
In Claude Code, type `/pragmatic-haskell-haskell-error-handling` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.
Can I share the haskell-error-handling skill with my team?
Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.