ErrorHandlingMiddleware
An opt-in error handling middleware that converts an error to an HTTP response.
struct ErrorHandlingMiddleware
Inclusion of ErrorHandlingMiddleware
should be accompanied by conforming errors to the HTTPResponseConvertible
protocol. Errors not conforming to HTTPResponseConvertible
are converted to a response with the 500 status code.
Example usage
Create an error type that conforms to the
HTTPResponseConvertible
protocol:
extension MyAppError: HTTPResponseConvertible {
var httpStatus: HTTPResponse.Status {
switch self {
case .invalidInputFormat:
.badRequest
case .authorizationError:
.forbidden
}
}
}
Opt into the
ErrorHandlingMiddleware
while registering the handler:
let handler = RequestHandler()
try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()])