From 1cefcd551b28ed549a1bc4ba1c1c2f72c624d975 Mon Sep 17 00:00:00 2001 From: Thomas Kowalski Date: Tue, 21 Apr 2026 08:45:33 +0200 Subject: [PATCH 1/2] fix: re-raise existing exception when available --- msgpack/_unpacker.pyx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/msgpack/_unpacker.pyx b/msgpack/_unpacker.pyx index f0cf96d7..e25986ee 100644 --- a/msgpack/_unpacker.pyx +++ b/msgpack/_unpacker.pyx @@ -205,7 +205,10 @@ def unpackb(object packed, *, object object_hook=None, object list_hook=None, raise FormatError elif ret == -3: raise StackError - raise ValueError("Unpack failed: error = %d" % (ret,)) + elif PyErr_Occurred(): + raise + else: + raise ValueError("Unpack failed: error = %d" % (ret,)) cdef class Unpacker: @@ -481,6 +484,8 @@ cdef class Unpacker: raise FormatError elif ret == -3: raise StackError + elif PyErr_Occurred(): + raise else: raise ValueError("Unpack failed: error = %d" % (ret,)) From 2e541230ab37b4093e10c75da5e4f80097a9ce39 Mon Sep 17 00:00:00 2001 From: Thomas Kowalski Date: Tue, 21 Apr 2026 10:50:40 +0200 Subject: [PATCH 2/2] test: add tests for re-raising exceptions --- test/test_except.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/test/test_except.py b/test/test_except.py index b77ac800..c56a6a30 100644 --- a/test/test_except.py +++ b/test/test_except.py @@ -4,7 +4,7 @@ from pytest import raises -from msgpack import FormatError, OutOfData, StackError, Unpacker, packb, unpackb +from msgpack import ExtType, FormatError, OutOfData, StackError, Unpacker, packb, unpackb class DummyException(Exception): @@ -32,6 +32,34 @@ def hook(obj): ) +def test_raise_from_list_hook(): + def hook(lst: list) -> list: + raise DummyException + + with raises(DummyException): + unpackb(packb([1, 2, 3]), list_hook=hook) + + with raises(DummyException): + unpacker = Unpacker(list_hook=hook) + unpacker.feed(packb([1, 2, 3])) + unpacker.unpack() + + +def test_raise_from_ext_hook(): + def hook(code: int, data: bytes) -> ExtType: + raise DummyException + + packed = packb(ExtType(42, b"hello")) + + with raises(DummyException): + unpackb(packed, ext_hook=hook) + + with raises(DummyException): + unpacker = Unpacker(ext_hook=hook) + unpacker.feed(packed) + unpacker.unpack() + + def test_invalidvalue(): incomplete = b"\xd9\x97#DL_" # raw8 - length=0x97 with raises(ValueError):