#๐Ÿ”’ error handling an except

73 messages ยท Page 1 of 1 (latest)

wide tangle
#

trying to figure out a nice way how i can better handle an error

glacial compassBOT
#

@wide tangle

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

wide tangle
#
    def fetch_video_transcript(video_id):
        try:
            transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['en'])
            youtube_transcript = " ".join([item['text'] for item in transcript]).replace('\n', ' ')

            return youtube_transcript

        except NoTranscriptFound:
            print(f"Geen transcript gevonden voor video {video_id}.")
            return "Transcript niet beschikbaar"

        except TranscriptsDisabled:
            print(f"Transcript is uitgeschakeld voor video {video_id}.")
            return "Transcript uitgeschakeld"

        except VideoUnavailable:
            print(f"Video {video_id} is niet beschikbaar.")
            return "Video niet beschikbaar"

        except Exception as e:
            print(f"Fout bij het ophalen van transcript voor video {video_id}: {e}")
            return None
#
    for video_file in video_files:
        video_id = video_file.split('.')[0]
        video_url = youtube_base_url + video_id
        youtube_transcript = fetch_video_transcript(video_id)
        sentimentwaarde = analyze_sentiment(youtube_transcript)
        print(youtube_transcript[:50])
        print(sentimentwaarde)

        if not youtube_transcript:
            print(f"Leeg of niet-beschikbaar transcript voor video {video_id}")
            continue

        if sentimentwaarde is None:
            print(f"Geen sentimentwaarde beschikbaar voor video {video_id}")
            continue
#

Fout bij het ophalen van transcript voor video HsmOJ4Xbfp4: no element found: line 1, column 0
Error analyzing sentiment: 'NoneType' object has no attribute 'lower'
Er is een fout opgetreden: 'NoneType' object is not subscriptable

#

just wondering how i can manage this better have a lot of videos so doesn t matter if one fails ๐Ÿ™‚

sweet coral
#

It's generally not a good idea to return multiple types from a function; especially when you're using the same types for success and failure cases. Here, you're returning strings for some error cases, None for the catch-all case, and a string in the success case. Does it even make sense to pass the error strings to analyze_sentiment? Why would you analyze the sentiment of an error message?

I'd probably move the try out of fetch_video_transcript and into the second block of code, and only run analyze_sentiment and such in the success case.

wide tangle
sweet coral
#

And because you're using the same type (strings) for both error and success cases, it will likely be impossible to differentiate between success and failure accurately by just looking at the strings.

I don't think it makes sense for fetch_video_transcript to catch the errors since it is unable to properly handle the error cases anyway. You should only catch errors when/where they can be handled.

wide tangle
#

won t this fix it?

sweet coral
#

No.

#

I meant:

def fetch_video_transcript(video_id):
    transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['en'])
    youtube_transcript = " ".join([item['text'] for item in transcript]).replace('\n', ' ')

    return youtube_transcript

for video_file in video_files:
    video_id = video_file.split('.')[0]
    video_url = youtube_base_url + video_id
    try:
        youtube_transcript = fetch_video_transcript(video_id)
        sentimentwaarde = analyze_sentiment(youtube_transcript)
        print(youtube_transcript[:50])
        print(sentimentwaarde)

    except NoTranscriptFound:
        print(f"Geen transcript gevonden voor video {video_id}.")
    . . . # All the other 'except's if you want special error messages.
#

There, now fixed

wide tangle
sweet coral
wide tangle
#

print(sentimentwaarde)

sweet coral
wide tangle
#

and in what way will this prevent
Fout bij het ophalen van transcript voor video jx4q82a6jHc: no element found: line 1, column 0
Error analyzing sentiment: 'NoneType' object has no attribute 'lower'
Er is een fout opgetreden: 'NoneType' object is not subscriptable

#

because it still gets stuck on the error?

eternal elm
#

they're just telling you to wrap the call to analyze_sentiment in a try-except

sweet coral
wide tangle
sweet coral
eternal elm
#

why not just move this code above the call to analyze_sentiment?

if not youtube_transcript:
    print(f"Leeg of niet-beschikbaar transcript voor video {video_id}")
    continue
wide tangle
wide tangle
sweet coral
wide tangle
eternal elm
#

c/p this and let us know

for video_file in video_files:
    video_id = video_file.split('.')[0]
    video_url = youtube_base_url + video_id
    youtube_transcript = fetch_video_transcript(video_id)
    if not youtube_transcript:
        print(f"Leeg of niet-beschikbaar transcript voor video {video_id}")
        continue
    sentimentwaarde = analyze_sentiment(youtube_transcript)
    print(youtube_transcript[:50])
    print(sentimentwaarde)
    if sentimentwaarde is None:
        print(f"Geen sentimentwaarde beschikbaar voor video {video_id}")
        continue
sweet coral
eternal elm
#

i don't disagree ๐Ÿ™‚

sweet coral
wide tangle
#

but why will that avoid the errors and this won t because looks pretty similair

wide tangle
eternal elm
#

because fetch_video_transcript returns None on a general exception and you pass None to analyze_sentiment which is expecting a string

sweet coral
wide tangle
eternal elm
#

i moved the test for youtube_transcript being falsy to before the call to analyze_sentiment instead of after it

wide tangle
eternal elm
#

test explicitly for is None if it makes more sense to you

wide tangle
eternal elm
#

where? your original code has if not youtube_transcript after

sweet coral
wide tangle
eternal elm
#

this is the original code you pasted

for video_file in video_files:
    video_id = video_file.split('.')[0]
    video_url = youtube_base_url + video_id
    youtube_transcript = fetch_video_transcript(video_id)
    sentimentwaarde = analyze_sentiment(youtube_transcript)
    print(youtube_transcript[:50])
    print(sentimentwaarde)

    if not youtube_transcript:
        print(f"Leeg of niet-beschikbaar transcript voor video {video_id}")
        continue

    if sentimentwaarde is None:
        print(f"Geen sentimentwaarde beschikbaar voor video {video_id}")
        continue
#

it is certainly after and not before

wide tangle
eternal elm
#

good luck @sweet coral !

#

๐Ÿซก

sweet coral
#

Ha, thanks.

wide tangle
wide tangle
#

@sweet coral is this ok?

sweet coral
#

I'd need to see more context, but this still has the issue where error strings will be passed to analyze_sentiment, which is why I recommended moving error handling out of the fetch function.

#

The way the other guy suggested only works well if None is returned in all error cases (which I suspect they were leading you towards).

wide tangle
sweet coral
#

The continue causes it to be skipped.

wide tangle
#

but should i try this what i have now? pr the other thingy?

eternal elm
#

all i did is move this code up

#

this assumes you don't care that you're passing those error strings to analyze_sentiment

#

if you do care about that, then do it as carc is suggesting

wide tangle
#

alr seems to work thank you just scared it breaks later cuz my code sometimes also ran fine ๐Ÿ˜…

wide tangle
# wide tangle

is there any chance it will break alter with the same code?

#

alr will close it thank you ๐Ÿ™‚

#

!close

glacial compassBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.