getCaughtMiddleware<T> function

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

Catches errors in the middleware chain

Example:

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

  throw error;
})

Without a snippet, it would look like this:

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

    throw error;
  }
};

Implementation

// ignore: prefer_expression_function_bodies
Middleware<T> getCaughtMiddleware<T>(CaughtMiddlewareHandler<T> errorHandler) {
  return (context, next) async {
    try {
      await next();
    } on Exception {
      return errorHandler(context, errorHandler as Exception);
    }
  };
}