`except`块在Python的`try`块中不起作用。

huangapple go评论72阅读模式
英文:

except block is not working in try except in python

问题

我试图从AWS Lambda(Python)中的特定命名空间获取Pod列表。

当我传递正确的命名空间时,它会返回正确和预期的Pod列表。但是,当我传递错误的命名空间时,它不会跳过try块,并且不会捕获except块以返回正确的响应。有什么原因吗?

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)
英文:

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)

答案1

得分: 3

问题似乎与您的 try/except 错误处理位置有关。
在您当前的代码中,您将 try/except 放在循环内,该循环遍历每个项。这意味着它只在将 pod 名称添加到 retList 或在 response_output 中设置 'Pods' 字段时才会捕获错误。

但是,您预期的错误 - ApiException - 可能会在尝试使用 apiCoreclient.list_namespaced_pod(namespace) 列出命名空间中的 pod 时发生。此行位于您的 try/except 块之外,因此如果在那里发生 ApiException,它不会被您的错误处理捕获。

为了解决这个问题,您应该将 try/except 块移动到包含 apiCoreclient.list_namespaced_pod(namespace) 行的范围内。以下是一个调整后的函数示例,以说明这一点:

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)

在这个改进版本中,如果在尝试列出命名空间中的 pod 时发生 ApiException,它将被捕获,并创建正确的错误响应。

英文:

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.

huangapple
  • 本文由 发表于 2023年6月22日 12:14:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定