'How to handle tweepy's "Stream encountered HTTP error: 406" error

so guys, i know that the Stream found HTTP error: 406 error only occurs when the user is wrong or doesn't exist, the problem is that only this is printed, it doesn't say on which line it occurs, so I would like to know how to deal with such an error so the code stops whenever it occurs as in my code if the user is wrong then the code will keep displaying the error and execution will continue infinitely

class Linstener(tweepy.Stream):

                
    def on_status(self, status):
        tweets = f"{status.user.screen_name}: {status.text}"
        print(tweets)


stream_tweet = Linstener(consumer_key, consumer_secret, access_token, access_token_secret)

              
try:
    stream_tweet.filter(follow=['user'])
except:
    stream_tweet.disconnect() # i tried to disconnect here in case the user is wrong or doesn't exist, however, as you imagine, it didn't work


Solution 1:[1]

if it did not work in the try statement, then the code has not connected.

This would mean that the disconnect would fail in the except section (given that it was never connected in the first place).

So to use this for the try statement:

try:
    stream_tweet.filter(follow=['user'])
except Exception as e:
    print(e)

Let me know if that works for you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 D.L