-
Daily Log:
- How to Handle Exceptions
-
Metadata:
- #article #programming #python
-
A typical flow may require several services and anyone of the services can break and interrupt the flow
-
Instead of writing a pattern that is repeated try-except with every service like creating a class and creating a function that logs all the different errors
- Which is hard to maintain and is focused on writing the errors
-
Make exceptions specific
- raise specific errors instead of raising generic exception
try: order_status = status_service.get_order_status(order_id) except Exception as e: logger.exception("...{e}...") raise e -
Mind your own business
- Don’t teach classes what can go wrong, instead have multiple classes to handle each thing and then use a single try…except… block
- Don’t have to re-raise errors, just use raise
class StatusService: def get_order_status(order_id): try: pass except: raise CustomError() from e class ReceiptService: def create(order_id): try: pass except: raise ReceiptGenerationFailed() from e class OrderService: def emit(self, order_id: str) -> dict: try: # all the services in here except OrderNotFound as e: # handle this except ReceiptGenerationFailed as e: # handle this- Better logging
- Tell don’t ask
- logging exceptions shouldn’t need to pass the exception because it is already implicit
- Let the downstream exception class to log the exact message
- Catching and raising exceptions effectively
- Instead of catching and re-raising, according to PEP3134 it is enough to just plainly raise or raising from another exception
- Logging exceptions effectively
- Don’t log the exception object, use logging.exception function to handle the stack trace
-
- How to Handle Exceptions
-
Retrospective::
- One week ago: May 13th, 2021
- One month ago: April 20th, 2021
- One quarter ago: February 20th, 2021
- One year ago: May 20th, 2020
-
Daily Stoic::
- When it comes to learning focus on quality over quantity, you will never read all the literature available in the world but you can benefit from reading from a few