Thank you for the discussion. This got me interested into what other projects are currently doing.
It looks like mutating exceptions to add messages is a very common pattern:
Some have defined utils like me:
But it looks like the most common pattern by far is to mutate e.args
:
Searching for exc.args =
, err.args =
, e.args =
, e.args +=
,⌠allow to find thoushands of examples of people augmenting extension with error messages.
Here again, we can see many users add the note before the exception:
e.args = ("Problem installing fixtures: %s" % e,)
e.args = (f'Error encountered while resolving {xbns_dir}: {e.args[0]}'
e.args = (self._add_line_info(e.args[0], pos),)
e.args = ("In '%s': %s" % (instance_class, e),)
e.args = ("The following error happened while"
" compiling the node", node, "\n") + e.args
e.args = (f"While constructing an argument of type {arg_annotation}",) + e.args
e.args = (f"Error from {key} dataset", *e.args)
...
And thereâs many, many more examplesâŚ
Hereâs another simpler proposal: Have a mutable e.__message__: str
.
The first time is accessed it would default to str(e)
, but could be mutated:
try:
fn()
except Exception as e:
e.__message__ = 'Error in fn: ' + e.__message__
raise
- This is simpler for the end user than the current PEP.
- This allow arbitrary nesting of try/catch
- This is more flexible
- This is the API stackoverflow users expected
This is somewhat similar to what was originally proposed in this PEP, but without the drawbacks:
What would the drawback ?
-
str(e)
would be computed during the first e.__message__
call. But is it really an issue in practice ? All the current reraise
implementations have this âlimitationâ currently !
- It isnât possible to track individual notes which have been added. Is it really an issue in practice ? (If really required it would be possible to track the history of messages in some
e.__messages__ = [msg0, msg1, ...]
)
For me, the benefits largely outweighs the drawback.
I would find it a little sad if this new PEP is not able to replace the the implementation of the thoushands of users who actually needed this.