Search code examples
pythonamazon-web-serviceskubernetesaws-lambdaamazon-eks

except block is not working in try except in python


I am trying to get list of pods from specific namespace in aws lambda (python).

Its giving right and expected list of pods. But When I pass wrong namespace, it is not skipping the try block and not catching the except block to return the correct response. Any reason for this ?

import json
from kubernetes.client.rest import ApiException

def get_pods(namespace: str, apiCoreclient: object):

    response_output = {}
    response_output["statusCode"] = 200    

    retList = []
    items = apiCoreclient.list_namespaced_pod(namespace).items
    for item in items:
        try:
            retList.append(item.metadata.name)
            response_output['Pods'] = json.dumps({"Pods": retList})

        except ApiException as e:
            response_output["error"] = e.reason
            response_output["statusCode"] = e.status

    response_output["isBase64Encoded"] = "False"       
    return json.dumps(response_output)

Solution

  • The issue seems to be tied to the location of your try/except error handling. In your current code, you've placed the try/except inside the loop that goes through each item. This means that it only catches errors when you're adding the pod name to the retList or setting the 'Pods' field in the response_output.

    But the error you're anticipating - an ApiException - would probably occur when you attempt to list the pods in the namespace with apiCoreclient.list_namespaced_pod(namespace). This line is outside your try/except block, so if an ApiException happens there, it's not going to be caught by your error handling.

    To remedy this, you should shift your try/except block to encompass the apiCoreclient.list_namespaced_pod(namespace) line. Here's a tweaked version of your function to illustrate this:

    def get_pods(namespace: str, apiCoreclient: object):
        response_output = {}
        response_output["statusCode"] = 200    
        retList = []
    
        try:
            items = apiCoreclient.list_namespaced_pod(namespace).items
            for item in items:
                retList.append(item.metadata.name)
            response_output['Pods'] = json.dumps({"Pods": retList})
    
        except ApiException as e:
            response_output["error"] = e.reason
            response_output["statusCode"] = e.status
    
        response_output["isBase64Encoded"] = "False"       
        return json.dumps(response_output)
    

    In this refined version, if an ApiException arises when you try to list the pods in the namespace, it will be caught and the correct error response will be created.