toParsedYamlException function

ParsedYamlException toParsedYamlException(
  1. CheckedFromJsonException exception, {
  2. YamlMap? exceptionMap,
})

Returns a ParsedYamlException for the provided exception.

This function assumes exception.map is of type YamlMap from package:yaml. If not, you may provide an alternative via exceptionMap.

Implementation

ParsedYamlException toParsedYamlException(
  CheckedFromJsonException exception, {
  YamlMap? exceptionMap,
}) {
  final yamlMap = exceptionMap ?? exception.map as YamlMap;

  final innerError = exception.innerError;

  if (exception.badKey) {
    final key = (innerError is UnrecognizedKeysException)
        ? innerError.unrecognizedKeys.first
        : exception.key;

    final node = yamlMap.nodes.keys.singleWhere(
        (k) => (k as YamlScalar).value == key,
        orElse: () => yamlMap) as YamlNode;
    return ParsedYamlException(
      exception.message!,
      node,
      innerError: exception,
    );
  } else {
    if (exception.key == null) {
      return ParsedYamlException(
        exception.message ?? 'There was an error parsing the map.',
        yamlMap,
        innerError: exception,
      );
    } else if (!yamlMap.containsKey(exception.key)) {
      return ParsedYamlException(
        [
          'Missing key "${exception.key}".',
          if (exception.message != null) exception.message!,
        ].join(' '),
        yamlMap,
        innerError: exception,
      );
    } else {
      var message = 'Unsupported value for "${exception.key}".';
      if (exception.message != null) {
        message = '$message ${exception.message}';
      }
      return ParsedYamlException(
        message,
        yamlMap.nodes[exception.key] ?? yamlMap,
        innerError: exception,
      );
    }
  }
}