[ bsd3, library, program, web ] [ Propose Tags ]

Extensible exceptions for servant APIs

[Skip to Readme]
Versions [faq] 0.1.0, 0.1.1
Change log
Dependencies aeson, base (>=4.7 && <5), exceptions, http-media, http-types, mtl, servant, servant-exceptions, servant-server, text, wai, warp [details]
License BSD-3-Clause
Copyright 2017 Sebastian Nagel
Author Sebastian Nagel
Category Web
Home page
Source repo head: git clone
Uploaded by ch1bo at 2018-01-23T20:08:07Z
Distributions LTSHaskell:0.1.1, NixOS:0.1.1
Executables example
Downloads 1063 total (29 in the last 30 days)
Rating (no votes yet) [estimated by Bayesian average]
Your Rating
  • λ
  • λ
  • λ
Status Hackage Matrix CI
Docs available [build log]
Last success reported on 2018-01-23 [all 1 reports]




Maintainer's Corner

For package maintainers and hackage trustees

Readme for servant-exceptions-0.1.1

[back to package description]


Servant servers typically run their handlers in some form of IO. Either directly in the builtin Handler monad or a custom monad transformer on top it. When APIs fail, one would typically use the MonadError ServantError instance via throwError to create an error response of type ServantErr.

This approach has two problems:

  • Handler (basically being ExceptT ServantErr IO) is considered an anti-pattern by some, as it suggests to novice users that only ServantErr would occur, but in IO any exception can be raised to abort execution
  • ServantErr values need to be created at the call site of throwError, where the requested content type and/or headers are not available

servant-exception tries to help with both by making it easy to catch specific error types with an instance of Exception and provide automatic encoding into the requested content-type.

The API combinator Throws e can be used to catch exceptions of type e in the server, for example:

type API = "api" :> Throws UsersError :> "users" :> Get '[JSON, PlainText] [User]

The type UsersError can then be used to describe expected errors and their conversion via type class instances:

data UsersError = UserNotFound
                | UserAlreadyExists
                | InternalError
                deriving (Show)

instance Exception UsersError

instance ToServantErr UsersError where
  status UserNotFound = status404
  status UserAlreadyExists = status409
  status InternalError = status500

instance ToJSON UsersError where
  toJSON e = object [ "type" .= show (typeOf e)
                    , "message" .= message e

instance MimeRender PlainText UsersError where
  mimeRender ct = mimeRender ct . show


This package is still a work-in-progress and lacks at least

  • Documentation, more examples
  • servant-client support
  • servant-docs support


This package is inspired by servant-checked-exceptions (Throws combinator) and the generalized error handling in cardano-sl.