defineExceptionFilter<T> function

Future<Response> Function(Event event) defineExceptionFilter<T>(
  1. FutureOr<Response?> process(
    1. Event event,
    2. ExceptionSource<T> source
    )
)

Define exception filter.

Many times, using ExceptionFilter to create filters can be cumbersome, especially when we have a simple exception that requires friendly handling. Using defineExceptionFilter is an easier option.

app.use(defineExceptionFilter<Error>((event, source) {
    return Response.json(status: 412, {
        "message": Error.safeToString(source.exception),
        "code": -1,
    });
}));

Implementation

Future<Response> Function(Event event) defineExceptionFilter<T>(
    FutureOr<Response?> Function(Event event, ExceptionSource<T> source)
        process) {
  return (Event event) async {
    try {
      return await next(event);
    } catch (exception, stackTrace) {
      if (exception is T) {
        final response =
            await process(event, ExceptionSource(exception as T, stackTrace));
        if (response != null) {
          return response;
        }
      } else if (exception is Response) {
        return exception;
      }

      rethrow;
    }
  };
}