Swiftpack.co - Package - skelpo/APIErrorMiddleware


A middleware to catch errors from route handlers and other middleware, and convert them to a JSON response.


Add the package declaration to your project's manifest dependencies array:

.package(url: "https://github.com/skelpo/APIErrorMiddleware.git", from: "0.1.0")

Then add the APIErrorMiddleware library to the dependencies array of any target you want to access the module in.


If you only want APIErrorMiddleware on some of your routes, you can create a new route group and register your routes with it:

let api = router.group(APIErrorMiddleware())

However, if you are creating an API service and want all errors to be caught by the middleware, you probably want to add it to the your MiddlewareConfig. In configure.swift, import the APIErrorMiddleware module. The body of the configure(_:_:_:) function probably has a MiddlewareConfig instance in it. If not, create one and register it with the services.

You can register the middleware to the MiddlewareConfig using:


Most likely, you will want to register this middleware first. This ensures that all the errors are caught and we don't have any thrown after its responder is run. There are some that you might want to run afterwards though, such as Vapor's built in DateMiddleware.


This middleware supports custom specializations which convert a Swift Error to a message and status code for the response returned by the middleware.

To add specializations to the middleware, initialize it with the ones to use:

middlewares.use(APIErrorMiddleware(specializations: [

The specializations available the package are the following:

  • ModelNotFound: Catches the modelNotFound error thrown by Fluent when getting a model from a parameter and converts it to a 404 error.

To create your own specializations, just conform any type to ErrorCatchingSpecialization and implement the convert(error:on:) method.


Stars: 19
Help us keep the lights on



0.3.5 - Jul 24, 2018

Compilation error fix!

0.3.4 - Jul 23, 2018

Custom headers are now supported! Thanks @Cellane !

0.3.3 - May 29, 2018

Error JSON Encoding Failure Error

Instead of having an empty body for the response body when JSON encoding fails, we use a string value that tells you what went wrong.

0.3.2 - May 25, 2018

Debug the Debuggable

Added a case to the error conditions in the APIErrorMIddleware responder for Debuggable errors when the app is in a dev environment.

Also added a compiler conditional so you don't get warnings about casting an Error to CustomStringConvertible always succeeding. Because it doesn't. On Linux that is.

0.3.1 - May 9, 2018

For some reason linux throws "APIErrorMiddleware.swift:92:31: error: 'Error' is not convertible to 'CustomStringConvertible'; did you mean to use 'as!' to force downcast?".

This is not fixed though it generates a warning for Mac. The warning is of no meaning though.