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: 10
Help us keep the lights on


Used By

Total: 0


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.

0.3.0 - May 7, 2018

The 3rd Vapor

Now uses the official 3.0 release of Vapor 💪.

0.2.2 - May 3, 2018

If the Promise don't Succeed, Try, Try Again.

Apparently returning the result of next.respond(to:) was a bad idea, so now we only return response.futureResult. We don't have errors escaping the middleware anymore 🙂.

0.2.1 - May 3, 2018

Fixed Bad Synth

Public structs don't get public synthesized initializers. Bah! So the ModelNotCreated struct now has an initializer.

0.2.0 - May 1, 2018


Create custom error handlers for converting specific errors to specific responses.