pythonexceptionimdbpy

IMDbPy : How can I catch IMDbDataAccessError?


I am completely noob at handling exceptions and I've been learning to work with IMDbPy. I wanted to catch the exception if a user enters an invalid ID. I tried

import imdb
from imdb import IMDbDataAccessError
ia = imdb.IMDb(accessSystem='http')
try:
    movie = ia.get_movie('12121212212121')
except IMDbDataAccessError:
    print("error")

But it doesn't print the text "error" rather it shows the error message. Which is -

IMDbDataAccessError exception raised; args: ({'errcode': None,
'errmsg': 'None', 'url':
'https://www.imdb.com/title/tt12121212212121/reference', 'proxy': '',
'exception type': 'IOError', 'original exception': <HTTPError 404:
'Not Found'>},); kwds: {}

Solution

  • import imdb
    from imdb import IMDbDataAccessError
    try:
        ia = imdb.IMDb(accessSystem='http', reraiseExceptions=True)
        movie = ia.get_movie('12121212212121')
    except:
        print("error")
    

    The option to reraiseExceptions helps. Now the program outputs the trace AND afterwards error. Note that since May 2021 reraiseExceptions=True should already be the default.


    I found this by looking at the source of the functions that raised the Exception. i.e. retrieve_unicode and update. Searching for "ret = method(mopID)" I found this which only raises the exception again if self._reraise_exceptions is set to true in the IMDB Base object.

    I created an issue asking them to please make it more obvious that this setting is necessary. The creator replied:

    I think it would be better to just always raise the exception.
    I'll consider the change for a future release.


    Also worth noting is this excerpt of their config:

    ## Set the threshold for logging messages.
    # Can be one of "debug", "info", "warning", "error", "critical" (default:
    # "warning").
    #loggingLevel = debug
    

    which implies that you can reduce the verbosity of the logs. However, passing a loggingLevel="critical" parameter does not seem to reduce the console output. That is because these errors are themselves of the level critical.
    However, you can disable the logger completely:

    import imdb
    from imdb import IMDbDataAccessError
    import logging
    try:
        logger = logging.getLogger('imdbpy');
        logger.disabled = True
        ia = imdb.IMDb(accessSystem='http', reraiseExceptions=True, loggingLevel="critical")
        movie = ia.get_movie('12121212212121')
    except IMDbDataAccessError:
        print("error")
    

    The names of the loggers are currently 'imdbpy' and 'imdbpy.aux'.


    update May 2021

    There has been some activity on the github issue:

    Just committed a change to the default behavior: now if not specified reraiseExceptions is True.

    This means that any exception is re-raised.

    If this breaks something important let us know, but I think this should be better handled catching the exception in the caller code.