【问题标题】:python exception within if and try blockif 和 try 块中的 python 异常
【发布时间】:2015-09-29 13:25:38
【问题描述】:

我正在使用请求将 python 客户端写入 Web 服务 (REST)

我想提出,除非用户输入了错误的凭据

我有以下代码块

    try:
        ret=self.req_session.get(URL)
        if (ret.status_code == 401):
            raise Authexecption("Improper credentials")
        else:
            ret.raise_for_status()               
    except Authexecption:
        logging.error("Unable to authenticate. Please check you credentails")
    except requests.exceptions.HTTPError:
        logging.error("Issue with communicating with Web-Services. The HTTP response is " + str(ret.status_code))
    except requests.exceptions.Timeout:
        logging.error("Time out while connecting to the Web-Service..")

这里的想法是,我将为身份验证问题提出一个自定义错误消息,并为所有其他问题(5xx、404 等)提出一个通用错误消息。

执行此操作时出现以下错误

    except Authexecption:
NameError: global name 'Authexecption' is not defined

我对python很陌生,正在努力学习,我该如何解决这个问题?

-提前致谢

【问题讨论】:

  • 嗯,你定义Authexecption了吗?您的意思是不是 Authexception(拼写正确)?

标签: python python-2.7 exception


【解决方案1】:

您需要先定义自定义异常:

class AuthException(Exception):  # Authexecption may be misspelled...
    pass

也许有比基本异常Exception 更好的异常可以继承。看看exception hierarchy

【讨论】:

  • 是的,我确实添加了它,但仍然收到相同的错误消息。我犯的错误是将 Authexecption 类与我调用此代码的类一起添加。我将这个类作为顶级类定义移动,它起作用了。谢谢
【解决方案2】:

错误说python找不到类Authexception。也就是说,它不存在或者没有被导入。

要解决这个问题,您需要先创建它:

class AuthException(Exception):
    def __init__(self, message, errors):
        # Call the base class constructor with the parameters it needs
        super(AuthException, self).__init__(message)

然后在需要的地方导入它。

【讨论】:

    猜你喜欢
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 2012-05-02
    • 1970-01-01
    • 2012-12-31
    • 2023-03-31
    • 2013-04-01
    相关资源
    最近更新 更多