Wraps unpickleable exceptions. Arguments: exc_module (str): See :attr:`exc_module`. exc_cls_name (str): See :attr:`exc_cls_name`. exc_args (Tuple[Any, ...]): See :attr:`exc_args`. Example: >>> def pickle_it(raising_function): ... try: ...
| 98 | |
| 99 | |
| 100 | class UnpickleableExceptionWrapper(Exception): |
| 101 | """Wraps unpickleable exceptions. |
| 102 | |
| 103 | Arguments: |
| 104 | exc_module (str): See :attr:`exc_module`. |
| 105 | exc_cls_name (str): See :attr:`exc_cls_name`. |
| 106 | exc_args (Tuple[Any, ...]): See :attr:`exc_args`. |
| 107 | |
| 108 | Example: |
| 109 | >>> def pickle_it(raising_function): |
| 110 | ... try: |
| 111 | ... raising_function() |
| 112 | ... except Exception as e: |
| 113 | ... exc = UnpickleableExceptionWrapper( |
| 114 | ... e.__class__.__module__, |
| 115 | ... e.__class__.__name__, |
| 116 | ... e.args, |
| 117 | ... ) |
| 118 | ... pickle.dumps(exc) # Works fine. |
| 119 | """ |
| 120 | |
| 121 | #: The module of the original exception. |
| 122 | exc_module = None |
| 123 | |
| 124 | #: The name of the original exception class. |
| 125 | exc_cls_name = None |
| 126 | |
| 127 | #: The arguments for the original exception. |
| 128 | exc_args = None |
| 129 | |
| 130 | def __init__(self, exc_module, exc_cls_name, exc_args, text=None): |
| 131 | safe_exc_args = ensure_serializable( |
| 132 | exc_args, lambda v: pickle.loads(pickle.dumps(v)) |
| 133 | ) |
| 134 | self.exc_module = exc_module |
| 135 | self.exc_cls_name = exc_cls_name |
| 136 | self.exc_args = safe_exc_args |
| 137 | self.text = text |
| 138 | super().__init__(exc_module, exc_cls_name, safe_exc_args, |
| 139 | text) |
| 140 | |
| 141 | def restore(self): |
| 142 | return create_exception_cls(self.exc_cls_name, |
| 143 | self.exc_module)(*self.exc_args) |
| 144 | |
| 145 | def __str__(self): |
| 146 | return self.text |
| 147 | |
| 148 | @classmethod |
| 149 | def from_exception(cls, exc): |
| 150 | res = cls( |
| 151 | exc.__class__.__module__, |
| 152 | exc.__class__.__name__, |
| 153 | getattr(exc, 'args', []), |
| 154 | safe_repr(exc) |
| 155 | ) |
| 156 | if hasattr(exc, "__traceback__"): |
| 157 | res = res.with_traceback(exc.__traceback__) |