How to translate the text of the Exceptions thrown by the datetime module? How to translate the text of the Exceptions thrown by the datetime module? flask flask

How to translate the text of the Exceptions thrown by the datetime module?


The short version: you should not: exceptions are meant to be acted upon, not translated.

There is conceptually a difference between a message intended for the user and a message intended for the developer (like runtime exceptions).

Translating exceptions would make as much sense as translating if ... then ... else constructs: the developer is supposed to know the programming language, not to need a translation of it.

While in the majority of the cases exceptions are caused by bugs (and therefore should not be there in deployed code), in some cases they might signal a condition that is physiological for the program. If this condition requires an action from the user, the code should catch the exception in question and present the user with a message that is meaningful for her/him. An example:

Knowing that:

>>> int('text')Traceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: invalid literal for int() with base 10: 'text'

You could write a program like this (of course using messages for the user in your favourite human language):

>>> while True:...     n = raw_input('What do you want to multiply 10 for?  ')...     try:...         print 'The result is: %d' % (10 * int(n))...     except ValueError:...         print 'You should provide an integer number...'

Note that we are catching only ValueError, as this is the only "physiological" case for our software. Any other exception would crash the program, as it would represent a condition the developer did not account for.

A word on validation though: if your scenario is that of a user having to insert a date in a specific format, it would be probably better to validate its input prior to try processing it. The above example should then become:

>>> while True:...     n = raw_input('What do you want to multiply 10 for?  ')...     if not all((c in '0123456789' for c in n)):...         print 'You should provide an integer number...'...         continue...     print 'The result is: %d' % (10 * int(n))

While in python it is mostly a matter of style whether to catch the exception or to validate the input (in other languages it might not be the case, as sometimes exceptions are much slower to process than checking for a condition), in web development is customary to also (i.e. additionally to check the input server-side, which you should always do) validate the input client-side with javascript, as this saves time to the user and CPU to the provider, eliminating a request/response cycle.

HTH!