On 2019-08-08 11:52, Ryan Fox wrote:
My proposal is a new exception class as the preferred base for user-defined exceptions:

>>> class MyException(ExceptionTemplate):
...    message = 'Bad thing happened during {action} in {context}'
>>> raise MyException(action=current_action, context=current_context)

The `message` string and the `MyException` class are 1-1; maybe you can remove more boilerplate and do it in one step:

> raise ExceptionUsingTemplate(
>     'Bad thing happened during {action} in {context}',
>     action=current_action,
>     context=current_context
> )

Plus, give it a shorter name:

> error(
>     'Bad thing happened during {action} in {context}',
>     action=current_action,
>     context=current_context
> )

You still have the "[templates] copied from place to place" problem; in those cases you raise the same type of error in many different locations, you can define a constant, and that constant represents the exception class:

> BAD_THING_HAPPENED = 'Bad thing happened during {action} in {context}'
> ...
> error(
>     BAD_THING_HAPPENED,
>     action=current_action,
>     context=current_context
> )

When catching exceptions, my code rarely cares about the specific type of exception, rather it only cares if an exception was raised.  But in a few rare cases the exception handler is discerning:

> except Exception as e:
>     if BAD_THING_HAPPENED in e:
>         # special case
>     else:
>         # all the other ways this failed
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/GN3ZCYWPRYGZSBXM67ZGVQGVM4I2XVMD/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to