1

I have a python flask app, pseudocode shown below.

@app.route('/predict', methods=['POST'])
    def transformation():
       try:
           var1 = function_1()
           # do something with var1
           var2 = function_2()
       except Exception as e:
           return jsonify({'message': '{}: {}'.format(type(e).__name__, e)}), 500

As you see, the POST call handler returns a generic exception message back to the client. But I want to customize those exception messages based on whether they are coming from function_1 or function_2

I looked into this thread and understand that it is possible to do below -

try:
 #something1
 #something2
except ExceptionType1:
 #return xyz
except ExceptionType2:
 #return abc

But how would it know that ExceptionType1 is coming from function_1() or function_2(). How should I pass exception from function_1() or function_2() to be caught in the main try-except block?

nad
  • 2,640
  • 11
  • 55
  • 96
  • Have you tried having two separate try-except blocks? So, like, one for function1 that will do something and another for function2? – Shreya Mar 14 '19 at 23:58
  • @SaberNomen I understand that is one way of doing it. But my main try-except block has 5-6 functions so was looking for a more generic way – nad Mar 15 '19 at 00:02
  • You could catch the exceptions in each function and `raise` a custom Exception for the route to catch. – Brendan Martin Mar 15 '19 at 00:05
  • @BrendanMartin can you show an example of how to raise a custom exception? My understanding is I need to override Exception class. But not sure how exactly – nad Mar 15 '19 at 00:08
  • Also, see if this helps: https://stackoverflow.com/questions/2380073/how-to-identify-what-function-call-raise-an-exception-in-python – Brendan Martin Mar 15 '19 at 00:08

0 Answers0