Skip to content

Commit ea35e64

Browse files
authored
fix: error handling decode_cf_var exceptions - use add_note (#10886)
1 parent 97f3a74 commit ea35e64

File tree

3 files changed

+10
-3
lines changed

3 files changed

+10
-3
lines changed

doc/whats-new.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ Bug Fixes
3939
``engine=`` argument. (:pull:`10804`). By `Ian Hunt-Isaak <https://github.com/ianhi>`_.
4040
- Fix indexing with empty arrays for scipy & h5netcdf backends which now resolves to empty slices (:issue:`10867`, :pull:`10870`).
4141
By `Kai Mühlbauer <https://github.com/kmuehlbauer>`_
42+
- Fix error handling issue in ``decode_cf_variables`` when decoding fails - the exception is now re-raised
43+
correctly, with a note added about the variable name that caused the error (:issue:`10873`, :pull:`10886`).
44+
By `Jonas L. Bertelsen <https://github.com/jonaslb>`_
4245

4346
Performance
4447
~~~~~~~~~~~

xarray/conventions.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -422,7 +422,8 @@ def stackable(dim: Hashable) -> bool:
422422
decode_timedelta=_item_or_default(decode_timedelta, k, None),
423423
)
424424
except Exception as e:
425-
raise type(e)(f"Failed to decode variable {k!r}: {e}") from e
425+
e.add_note(f"Raised while decoding variable {k!r} with value {v!r}")
426+
raise
426427
if decode_coords in [True, "coordinates", "all"]:
427428
var_attrs = new_vars[k].attrs
428429
if "coordinates" in var_attrs:

xarray/tests/test_conventions.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -658,8 +658,11 @@ def test_scalar_units() -> None:
658658

659659

660660
def test_decode_cf_error_includes_variable_name():
661-
ds = Dataset({"invalid": ([], 1e36, {"units": "days since 2000-01-01"})})
662-
with pytest.raises(ValueError, match="Failed to decode variable 'invalid'"):
661+
ds = Dataset({"my_invalid_var": ([], 1e36, {"units": "days since 2000-01-01"})})
662+
with pytest.raises(
663+
ValueError,
664+
match=r"unable to decode(?s:.*)my_invalid_var",
665+
):
663666
decode_cf(ds)
664667

665668

0 commit comments

Comments
 (0)