getCaughtMiddleware<T> function

Middleware<T> getCaughtMiddleware <T>(
  1. CaughtMiddlewareHandler<T> errorHandler
)

Catches errors in the middleware chain

Example:

getCaughtMiddleware((context, error) {
  if (error is HttpException) {
    return context.send('Sorry, network issues 😔');
  }

  throw error;
});

Without a snippet, it would look like this:

(context, next) async {
  try {
    await next();
  } catch (e) {
    if (e is HttpException) {
      return context.send('Sorry, network issues 😔');
    }

    rethrow e;
  }
}

Implementation

Middleware<T> getCaughtMiddleware<T>(
  CaughtMiddlewareHandler<T> errorHandler,
) {
  return (T context, FutureOr<void> Function() next) async {
    try {
      await next();
    } catch (e) {
      return errorHandler(context, e);
    }
  };
}