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?

5
  • Have you tried having two separate try-except blocks? So, like, one for function1 that will do something and another for function2? Commented Mar 14, 2019 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 Commented Mar 15, 2019 at 0:02
  • You could catch the exceptions in each function and raise a custom Exception for the route to catch. Commented Mar 15, 2019 at 0: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 Commented Mar 15, 2019 at 0:08
  • Also, see if this helps: stackoverflow.com/questions/2380073/… Commented Mar 15, 2019 at 0:08

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.