Get the error code from tweepy exception instance

前端 未结 5 640
猫巷女王i
猫巷女王i 2020-12-14 09:50

I\'m new to python and I\'m trying to use a library. It raises an exception, and I am trying to identify which one. This is what I am trying:

except tweepy.T         


        
5条回答
  •  遥遥无期
    2020-12-14 10:22

    To get just the error code use the method monq posted. The following example illustrates how to get both the error code and the message. I had to extract the message from the e.reason string, if anyone has a better method to retrieve just the message, please share.

    Note: This code should work for any error code/reason with the following format.

    [{'code': 50, 'message': 'User not found.'}]

    def getExceptionMessage(msg):
        words = msg.split(' ')
    
        errorMsg = ""
        for index, word in enumerate(words):
            if index not in [0,1,2]:
                errorMsg = errorMsg + ' ' + word
        errorMsg = errorMsg.rstrip("\'}]")
        errorMsg = errorMsg.lstrip(" \'")
    
        return errorMsg
    

    And you can call it like so:

    try:
        # Some tweepy api call, ex) api.get_user(screen_name = usrScreenName)
    except tweepy.TweepError as e:
        print (e.api_code)
        print (getExceptionMessage(e.reason))
    

提交回复
热议问题