diff --git a/lib/iris/cube.py b/lib/iris/cube.py index f58a2ce607..140e4f7113 100644 --- a/lib/iris/cube.py +++ b/lib/iris/cube.py @@ -2561,7 +2561,14 @@ def _repr_html_(self): from iris.experimental.representation import CubeRepresentation representer = CubeRepresentation(self) - return representer.repr_html() + # Catch exceptions in the html repr rather than passing them, + # and so fall back to the default cube repr. + try: + result = representer.repr_html() + except (IndexError, ValueError): + result = None + finally: + return result def __iter__(self): raise TypeError("Cube is not iterable") diff --git a/lib/iris/tests/unit/cube/test_Cube.py b/lib/iris/tests/unit/cube/test_Cube.py index 11860cb278..a5a379ecba 100644 --- a/lib/iris/tests/unit/cube/test_Cube.py +++ b/lib/iris/tests/unit/cube/test_Cube.py @@ -2411,5 +2411,19 @@ def test_cell_method_correct_order(self): self.assertTrue(cube1 == cube2) +@tests.skip_data +class Test__repr_html(tests.IrisTest): + def test_bad_repr(self): + # If an html repr fails we don't want it to pass the error. + cube = stock.simple_3d() + with mock.patch( + "iris.experimental.representation.CubeRepresentation.repr_html", + side_effect=ValueError("Bad substring"), + ): + # Confirm the exception when we make the html repr is not returned + # by the cube method. + self.assertIsNone(cube._repr_html_()) + + if __name__ == "__main__": tests.main()