0
I am working for the first time with an API and need to return an error if it occurs, follow my code with the clearest and simplest way I found to notify errors:
if request.method == 'POST':
try:
information = json.loads(request.data)
string_open = information['before']
string_closed = information['after']
except:
return 'Não foi possivel interpretar a requisição'
try:
results_open = tfnet.return_predict(readb64(string_open))
results_closed = tfnet.return_predict(readb64(string_closed))
except:
return 'Não foi possível converter a string64'
return jsonify(result_inventory)
I would like to know if there is any better way to write this code or some convention that regularizes the handling of exceptions in python.
If I call this function, how will I know, from the return, whether or not there was an error in the call to the API? How can I differentiate if the string that has been returned is due to an error or has the API actually returned? By the way, what are
jsonify
andresult_inventory
which are not defined in the code?– Woss
jsonify is the flask method for returning json, result_inventory is basically a json. So if returning a json in the expected format worked, otherwise it will return a string depending on where the error occurred.
– Filipe Gonçalves
So wouldn’t it be interesting to let the exception spread out of function and let whoever’s calling it treat it? It doesn’t seem to make much sense to capture an exception just to notify an error.
– Woss
But trying to figure out by the result whether it is normal string or json is worse and more laborious than catching the exception in the place where it is called the function.
– Isac
Right, so the best way to deal with this would be to return the mistake itself ?
– Filipe Gonçalves
The best way is to let the exception be propagated out of function, as @Andersoncarloswoss mentioned.
– Isac