1

I'm new to Python exception handling. How do I correctly try the following, except if .get_entity fails, but pass if Status 200?

Here is where I'm at:

  • Its not correct though. Hoping you could elaborate with an example.
from azure.cosmosdb.table.tableservice import TableService
from azure.cosmosdb.table.models import Entity
from azure.common import AzureMissingResourceHttpError

def get_table_row(TableName, PartitionKey, RowKey):
    try:
        table_lookup = table_service.get_entity(TableName, PartitionKey, RowKey)
    except AzureMissingResourceHttpError as e:
        logging.error(f'#### Status Code: {e.status_code} ####')
    finally:
        if e.status_code == 200:
            return table_lookup
        else:
            logging.error(f'#### Status Code: {e.status_code} ####')

data = get_table_row(TableName, PartitionKey, RowKey)
ericOnline
  • 1,586
  • 1
  • 19
  • 54

1 Answers1

2

You can change your code like below:

def get_table_row(TableName, PartitionKey, RowKey):
    try:
        table_lookup = table_service.get_entity(TableName, PartitionKey, RowKey)
    except AzureMissingResourceHttpError as e:
        if e.status_code == 200:
            return table_lookup
        else:
            logging.error(f'#### Status Code: {e.status_code} ####')
            return "whatever you want"
    else:
        return table_lookup
Hury Shen
  • 14,948
  • 1
  • 9
  • 18
  • Thank you @HuryShen; testing this now. – ericOnline Dec 04 '20 at 14:27
  • This worked with one caveat, though a `Status 404` was received, the Function continued past this point. How do I gracefully exit the Function at this point if `get_table_row` does not return `Status 200`? – ericOnline Dec 04 '20 at 14:45
  • 1
    Hi @ericOnline In the code above, if got 404, it will execute the code under first `else`: `logging.error(.....`, `return "whatever you want"`. What data returned is up to you, but in my opinion, if you want to response gracefully, you can assign an empty list to `table_lookup` and then `return table_loopup` there. – Hury Shen Dec 07 '20 at 01:50
  • Ok. So something like: If 404, under first `else:` add `table_lookup = None` and `return table_lookup`. Then when the function is called, `if table_lookup != None: "do things" else: logging.info("#### No entity found ####")`? – ericOnline Dec 07 '20 at 19:23
  • 1
    @ericOnline Yes – Hury Shen Dec 08 '20 at 02:22