ErrorHandlingMiddleware

An opt-in error handling middleware that converts an error to an HTTP response.

ErrorHandlingMiddleware.swift:46
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

  1. 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
       }
   }
}
  1. Opt into the ErrorHandlingMiddleware while registering the handler:

let handler = RequestHandler()
try handler.registerHandlers(on: transport, middlewares: [ErrorHandlingMiddleware()])