簡體   English   中英

if 和 try 塊中的 python 異常

[英]python exception within if and try block

我正在使用請求將 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 還很陌生,正在嘗試學習,我該如何解決這個問題?

-提前致謝

您需要先定義自定義異常:

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

也許有比基本異常Exception更好的異常可以繼承。 看看異常層次結構

錯誤說 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)

然后將其導入到您需要的任何位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM