discoverError static method

Map<String, List<String>> discoverError(
  1. List<Map<String, Object?>> response
)

Analyzes MongoDB error responses and extracts field-specific errors.

This method processes MongoDB write error responses and groups them by the fields that caused the errors. It's particularly useful for handling constraint violations, duplicate key errors, and validation failures.

The method looks for:

  • Write errors in the response
  • Error codes and their corresponding messages
  • Key patterns to identify affected fields

Parameters:

  • response - List of MongoDB server response objects

Returns a map where keys are field names and values are lists of error messages for those fields.

Example:

var errors = MongoErrorResponse.discoverError(responses);
// Result: {'email': ['duplicate key error'], 'name': ['required field']}

Implementation

static Map<String, List<String>> discoverError(
  List<Map<String, Object?>> response,
) {
  Map<String, List<String>> res = {};

  for (final resp in response) {
    if (resp.containsKey('writeErrors') && resp['writeErrors'] is List) {
      final writeErrors = resp['writeErrors'] as List;
      for (final writeError in writeErrors) {
        String error = mongoDBErrorCodes[writeError['code']]?[#name] ??
            'mongo.error.unknown';
        final Map<String, Object?> keyPattern =
            (writeError['keyPattern'] != null &&
                    writeError['keyPattern'] is Map)
                ? writeError['keyPattern']
                : {};
        List<String> fields = keyPattern.keys.toList();
        for (var field in fields) {
          if (!res.containsKey(field)) {
            res[field] = [];
          }
          res[field]!.add(error);
        }
      }
    }
  }

  return res;
}