Skip to content

FutureOr<T> are unnecessarily always awaited #870

Description

@ueman

The code from

Future<SentryEvent?> _processEvent(
SentryEvent event, {
dynamic hint,
required List<EventProcessor> eventProcessors,
}) async {
SentryEvent? processedEvent = event;
for (final processor in eventProcessors) {
try {
processedEvent = await processor.apply(processedEvent!, hint: hint);
} catch (exception, stackTrace) {
_options.logger(
SentryLevel.error,
'An exception occurred while processing event by a processor',
exception: exception,
stackTrace: stackTrace,
);
}
if (processedEvent == null) {
_recordLostEvent(event, DiscardReason.eventProcessor);
_options.logger(SentryLevel.debug, 'Event was dropped by a processor');
break;
}
}
return processedEvent;
}
can be rewritten as follows

Future<SentryEvent?> _processEvent(
  SentryEvent event, {
  dynamic hint,
  required List<EventProcessor> eventProcessors,
}) async {
  SentryEvent? processedEvent = event;
  for (final processor in eventProcessors) {
    try {
      // the 6 following lines are the important bit
      final e = processor.apply(processedEvent!, hint: hint);
      if(e is Future) {
        processedEvent = await e;
      } else {
        processedEvent = e;
      }
    } catch (exception, stackTrace) {
      _options.logger(
        SentryLevel.error,
        'An exception occurred while processing event by a processor',
        exception: exception,
        stackTrace: stackTrace,
      );
    }
    if (processedEvent == null) {
      _recordLostEvent(event, DiscardReason.eventProcessor);
      _options.logger(SentryLevel.debug, 'Event was dropped by a processor');
      break;
    }
  }
  return processedEvent;
}

This should improve performance a little. There are a couple more places where the code can be improved similarly.

This comes out of a discussion at #858 (comment)

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions