简体   繁体   English

if 和 try 块中的 python 异常

[英]python exception within if and try block

I'm writing a python client to a web-service (REST) using requests我正在使用请求将 python 客户端写入 Web 服务 (REST)

I want to raise except with the user enters bad credentials我想提高除非用户输入错误的凭据

I have the following code block我有以下代码块

    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..")

The Idea here being, that I will raise a custom error message for auth issues, and a generic one for all other issues (5xx,404 etc..)这里的想法是,我将针对身份验证问题提出自定义错误消息,并针对所有其他问题(5xx、404 等)提出通用错误消息。

when I execute this I get the following error当我执行此操作时,出现以下错误

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

I'm pretty new to python and trying to learn, how do i fix this?我对 python 还很陌生,正在尝试学习,我该如何解决这个问题?

-Thanks in advance -提前致谢

you need to define custom exceptions first:您需要先定义自定义异常:

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

maybe there is a better exception to inherit from than the base exception Exception .也许有比基本异常Exception更好的异常可以继承。 have a look at the exception hierarchy .看看异常层次结构

The error says that python cannot find the class Authexception .错误说 python 找不到类Authexception That is, it does not exist or it was not imported.也就是说,它不存在或未导入。

To fix this, you need to create it first:要解决此问题,您需要先创建它:

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

and then import it wherever you need.然后将其导入到您需要的任何位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM