mapErrors function

Middleware mapErrors(
  1. FutureOr<HubResponse?> map(
    1. Object error,
    2. StackTrace stackTrace
    )
)

Middleware that maps errors thrown by inner handlers to responses via map — the seam for translating an application's own exception hierarchy into HubResponses.

map returns a HubResponse to use, or null to rethrow (letting the hub's built-in errorMapper handle it — e.g. framework HubExceptions). Place this in the hub's user-middleware layer (it runs inside errorMapper).

Implementation

Middleware mapErrors(
  FutureOr<HubResponse?> Function(Object error, StackTrace stackTrace) map,
) {
  return (HubRequestHandler inner) {
    return (HubRequest request) async {
      try {
        return await inner(request);
      } on Object catch (e, s) {
        final mapped = await map(e, s);
        if (mapped != null) return mapped;
        rethrow;
      }
    };
  };
}