I hope this is not too opinion based, but I've understood that the Python community has some strong guidelines for how to use exception handling, though I couldn't find any commentary fitting to my situation.
I'm in the process of writing the main API function of a web-based script. The incoming data is first preprocessed/sanitized, then pushed through the complicated processing, and the result is finally postprocessed/formatted before being sent back to the requester. Each of the three parts can fail due to various reasons, so I need to wrap them into try-except blocks.
My question is: Is it more pythonic to wrap the whole process in one try-except -block an capture various types of exceptions, or to create individual blocks? I.e., of the following two styles, should I prefer one of them?
Version 1
def main(input_data):
try:
parsed_data = parse_incoming_data(input_data)
except LookupError as e:
return func.HttpResponse(f"Misformatted data, key not found: {e}", status_code=400)
try:
processed_data = big_process(parsed_data)
except CustomProcessingException as e:
return func.HttpResponse(f"Main service failed due to {e}.", status_code=500)
try:
output = postprocess_result(processed_data)
except CustomPostprocessingException as e:
return func.HttpResponse(f"Postprocessing error {e}.", status_code=555)
return func.HttpResponse(output, status_code=200)
Version 2
def main(input_data):
try:
parsed_data = parse_incoming_data(input_data)
processed_data = big_process(parsed_data)
output = postprocess_result(processed_data)
except LookupError as e:
return func.HttpResponse(f"Misformatted data, key not found: {e}", status_code=400)
except CustomProcessingException as e:
return func.HttpResponse(f"Main service failed due to {e}.", status_code=500)
except CustomPostprocessingException as e:
return func.HttpResponse(f"Postprocessing error {e}.", status_code=555)
return func.HttpResponse(output, status_code=200)