toJson method

Map<String, dynamic> toJson()

Serializes this event to JSON.

Implementation

Map<String, dynamic> toJson() {
  var messageMap = message?.toJson();
  final contextsMap = contexts.toJson();
  final userMap = user?.toJson();
  final sdkMap = sdk?.toJson();
  final requestMap = request?.toJson();
  final debugMetaMap = debugMeta?.toJson();
  final exceptionsJson = exceptions
      ?.map((e) => e.toJson())
      .where((e) => e.isNotEmpty)
      .toList(growable: false);

  // Thread serialization is tricky:
  // - Thread should not have a stacktrace when an exception is connected to it
  // - Thread should serializae a stacktrace when no exception is connected to it

  // These are the thread ids with a connected exception
  final threadIds = exceptions
      ?.map((element) => element.threadId)
      .where((element) => element != null)
      .toSet();

  final threadJson = threads
      ?.map((element) {
        if (threadIds?.contains(element.id) ?? false) {
          // remove thread.stacktrace if a connected exception exists
          final json = element.toJson();
          json.remove('stacktrace');
          return json;
        }
        return element.toJson();
      })
      .where((e) => e.isNotEmpty)
      .toList(growable: false);

  return <String, dynamic>{
    'event_id': eventId.toString(),
    if (timestamp != null)
      'timestamp': formatDateAsIso8601WithMillisPrecision(timestamp!),
    if (platform != null) 'platform': platform,
    if (logger != null) 'logger': logger,
    if (serverName != null) 'server_name': serverName,
    if (release != null) 'release': release,
    if (dist != null) 'dist': dist,
    if (environment != null) 'environment': environment,
    if (modules != null && modules!.isNotEmpty) 'modules': modules,
    if (transaction != null) 'transaction': transaction,
    if (level != null) 'level': level!.name,
    if (culprit != null) 'culprit': culprit,
    if (tags?.isNotEmpty ?? false) 'tags': tags,
    // ignore: deprecated_member_use_from_same_package
    if (extra?.isNotEmpty ?? false) 'extra': extra,
    if (type != null) 'type': type,
    if (fingerprint?.isNotEmpty ?? false) 'fingerprint': fingerprint,
    if (breadcrumbs?.isNotEmpty ?? false)
      'breadcrumbs':
          breadcrumbs?.map((b) => b.toJson()).toList(growable: false),
    if (messageMap?.isNotEmpty ?? false) 'message': messageMap,
    if (contextsMap.isNotEmpty) 'contexts': contextsMap,
    if (userMap?.isNotEmpty ?? false) 'user': userMap,
    if (sdkMap?.isNotEmpty ?? false) 'sdk': sdkMap,
    if (requestMap?.isNotEmpty ?? false) 'request': requestMap,
    if (debugMetaMap?.isNotEmpty ?? false) 'debug_meta': debugMetaMap,
    if (exceptionsJson?.isNotEmpty ?? false)
      'exception': {'values': exceptionsJson},
    if (threadJson?.isNotEmpty ?? false) 'threads': {'values': threadJson},
  };
}