createMiddleware function

Middleware createMiddleware (
  1. {FutureOr<Response> requestHandler(
    1. Request request
  2. FutureOr<Response> responseHandler(
    1. Response response
  3. FutureOr<Response> errorHandler(
    1. dynamic error,
    2. StackTrace stackTrace

Creates a Middleware using the provided functions.

If provided, requestHandler receives a Request. It can respond to the request by returning a Response or Future<Response>. requestHandler can also return null for some or all requests in which case the request is sent to the inner Handler.

If provided, responseHandler is called with the Response generated by the inner Handler. Responses generated by requestHandler are not sent to responseHandler.

responseHandler should return either a Response or Future<Response>. It may return the response parameter it receives or create a new response object.

If provided, errorHandler receives errors thrown by the inner handler. It does not receive errors thrown by requestHandler or responseHandler, nor does it receive HijackExceptions. It can either return a new response or throw an error.


Middleware createMiddleware(
    {FutureOr<Response> requestHandler(Request request),
    FutureOr<Response> responseHandler(Response response),
    FutureOr<Response> errorHandler(error, StackTrace stackTrace)}) {
  if (requestHandler == null) requestHandler = (request) => null;

  if (responseHandler == null) responseHandler = (response) => response;

  void Function(Object, StackTrace) onError;
  if (errorHandler != null) {
    onError = (error, stackTrace) {
      if (error is HijackException) throw error;
      return errorHandler(error, stackTrace);

  return (Handler innerHandler) {
    return (request) {
      return Future.sync(() => requestHandler(request)).then((response) {
        if (response != null) return response;

        return Future.sync(() => innerHandler(request))
            .then((response) => responseHandler(response), onError: onError);