According to what I've read EAFP (Easier to Ask for Forgiveness than Permission) is an accepted coding style in Python, actually recommended in many cases.
My question is about when that becomes too much with custom exceptions. Imagine we have a web application for a dog hotel with the following structure:
- controllers
-- dogs.py (Receives REST requests)
- services
-- dogs.py (Connects to a DB and a third party API to retrieve dog breed information)
-- validator.py
Now three requests examples:
- Someone wants to create a new dog, but gives invalid information. So the validator has a is_valid_dog method that returns False.
- Someone makes a GET request to retrieve information about a certain dog that does not exist. The dogs service hits the database but nothing is found.
- The user wants dog breed information, the service hits the third party API but it's down (500 status obtained).
What is the best way to handle that type of flow?
- In the first case, should I raise an exception when the is_valid_dog returns a False? or return None/False to the controller so it can map it to the 400 status code?
- Should I return None so the controller maps the return value to 404?
- Should I catch the exception and raise a custom ThirdPartyAPIException with the message and the controller must know how to handle that?
I'm curious about when to return specific values or just raise exceptions across different layers so the controller can return the final status. And in general, where is the best place to handle those exceptions/flows.