<p>I am trying to get list of pods from specific namespace in aws lambda (python).</p>
<p>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 ?</p>
<pre><code>import json
from kubernetes.client.rest import ApiException

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

    response_output = {}
    response_output[&quot;statusCode&quot;] = 200    

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

        except ApiException as e:
            response_output[&quot;error&quot;] = e.reason
            response_output[&quot;statusCode&quot;] = e.status

    response_output[&quot;isBase64Encoded&quot;] = &quot;False&quot;       
    return json.dumps(response_output)
</code></pre>

ctgopinaath
<p>The issue seems to be tied to the location of your <code>try/except</code> error handling.
In your current code, you've placed the <code>try/except</code> inside the loop that goes through each item. This means that it only catches errors when you're adding the pod name to the <code>retList</code> or setting the 'Pods' field in the <code>response_output</code>.</p>
<p>But the error you're anticipating - an <code>ApiException</code> - would probably occur when you attempt to list the pods in the namespace with <code>apiCoreclient.list_namespaced_pod(namespace)</code>. This line is outside your <code>try/except</code> block, so if an <code>ApiException</code> happens there, it's not going to be caught by your error handling.</p>
<p>To remedy this, you should shift your <code>try/except</code> block to encompass the <code>apiCoreclient.list_namespaced_pod(namespace)</code> line. Here's a tweaked version of your function to illustrate this:</p>
<pre><code>def get_pods(namespace: str, apiCoreclient: object):
    response_output = {}
    response_output[&quot;statusCode&quot;] = 200    
    retList = []

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

    except ApiException as e:
        response_output[&quot;error&quot;] = e.reason
        response_output[&quot;statusCode&quot;] = e.status

    response_output[&quot;isBase64Encoded&quot;] = &quot;False&quot;       
    return json.dumps(response_output)
</code></pre>
<p>In this refined version, if an <code>ApiException</code> arises when you try to list the pods in the namespace, it will be caught and the correct error response will be created.</p>
