Skip to content

fix: raise ValueError on malformed YAML instead of leaking the parser's exception (#282) - #291

Open
patchwright wants to merge 1 commit into
23andMe:masterfrom
patchwright:fix/malformed-yaml-value-error
Open

fix: raise ValueError on malformed YAML instead of leaking the parser's exception (#282)#291
patchwright wants to merge 1 commit into
23andMe:masterfrom
patchwright:fix/malformed-yaml-value-error

Conversation

@patchwright

Copy link
Copy Markdown

Problem

Fixes #282. When parse_yaml is given malformed YAML, the underlying parser's exception (PyYAML's yaml.scanner.ScannerError / ruamel's YAMLError) escapes as a raw stack trace instead of a clean error. Confirmed on master HEAD 5046af8.

Root cause

_pyyaml and _ruamel in yamale/readers/yaml_reader.py call yaml.load_all(...) without catching the parser's error, so it propagates straight out of parse_yaml.

Fix

Wrap each parser's load_all call in a try/except for its own error type (yaml.YAMLError for PyYAML, ruamel.yaml.YAMLError for ruamel) and re-raise as ValueError with the original message chained via from e. No API change; ~8 lines.

How to test

from yamale.readers import parse_yaml
parse_yaml(content='key: "unclosed', parser='pyyaml')
# before: yaml.scanner.ScannerError: while scanning a quoted scalar ... (stack trace)
# after:  ValueError: Could not parse YAML: while scanning a quoted scalar ...

Regression test added in yamale/readers/tests/test_bad_file.py, parametrized over pyyaml/PyYAML/ruamel. Full suite green (171 passed).

Backward compatibility

No breaking changes. Only the exception type for malformed input changes (raw parser error -> ValueError), which is the behavior requested in #282.


Assisted-by: Claude (code generation, reviewed and tested locally)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Handle not well-formed YAML files gracefully

1 participant