diff --git a/msgpack/_packer.pyx b/msgpack/_packer.pyx index a4913ab7..35e5a9dc 100644 --- a/msgpack/_packer.pyx +++ b/msgpack/_packer.pyx @@ -289,11 +289,13 @@ cdef class Packer(object): cpdef pack(self, object obj): cdef int ret - ret = self._pack(obj, DEFAULT_RECURSE_LIMIT) - if ret == -1: - raise MemoryError - elif ret: # should not happen. - raise TypeError + try: + ret = self._pack(obj, DEFAULT_RECURSE_LIMIT) + except: + self.pk.length = 0 + raise + if ret: # should not happen. + raise RuntimeError("internal error") if self.autoreset: buf = PyBytes_FromStringAndSize(self.pk.buf, self.pk.length) self.pk.length = 0 diff --git a/msgpack/fallback.py b/msgpack/fallback.py index d95f6218..675ee8a5 100644 --- a/msgpack/fallback.py +++ b/msgpack/fallback.py @@ -848,7 +848,11 @@ def _pack(self, obj, nest_limit=DEFAULT_RECURSE_LIMIT, raise TypeError("Cannot serialize %r" % (obj, )) def pack(self, obj): - self._pack(obj) + try: + self._pack(obj) + except: + self._buffer = StringIO() # force reset + raise ret = self._buffer.getvalue() if self._autoreset: self._buffer = StringIO()