So here’s an example of what I do on the front end part of a Vision (though could be perspective app as well) - the following would be on a submit button
#gather data
try:
myModule.saveData(data)
except FormError as e:
displayError(e)
And then inside my saveData(data)
, I have conditions that are checked. For instance
def saveData(data):
"""
data: dictionary of data
"""
if data['someMoneyField'] < 0:
raise FormError("Money field cannot be negative!")
....
So that first tidbit of code would catch the error that occurs when actually trying to save it, and then you can do with it as you wish to display it. In vision, a very easy way to do it would be
try:
myModule.saveData(data)
except FormError as e:
system.gui.messageBox(e)
to show a popup of the error. In perspective, you’ll probably want to make your own popup.
Note - FormError
, is a custom error I made, for situations where the user enters input that is considered not valid. You can and in some cases should make your own custom error types when appropriate. To do so
class FormError(Exception):
pass
is all you need, and then import this where needed.
Also, normally you don’t return the errorMsg like that - what if your try is completely successful, then your errorMsg would be None and that is what would be returning. Usually in situations where you are unsure of the errors you might get, you should at the least just log them to the gateway, so that your try/excepts can be better organized so that for errors you do now know occur, you can handle appropriately.
One of the general rules for coding python is that the “right” or clean way to code is to try to do something and then fail gracefully. However, when it comes to failing gracefully from other code that is up to you to write, the only way to actually even fail is if your other code does a raise ErrorOfSomeSort
somewhere.
I hope this makes sense.