vanna-ai / vanna

🤖 Chat with your SQL database 📊. Accurate Text-to-SQL Generation via LLMs using RAG 🔄.
https://vanna.ai/docs/
MIT License
9.97k stars 737 forks source link

fix: exceptions not caught with `except Exception as e:` #372

Closed Molrn closed 3 months ago

Molrn commented 3 months ago

Description

The exceptions defined in vanna.exceptions can not be catched with a try: ... except Exception as e:.

Reproduction

from vanna.exceptions import ValidationError

try:
    raise ValidationError()
except Exception as e:
    print("Caught with Exception")
# this raises an error

try:
    raise ValidationError()
except BaseException as e:
    print("Caught with BaseException")
# This does not

Explanation

Vanna exceptions are all derived from the class BaseException instead of the class Exception.

class ValidationError(BaseException):
class Exception(BaseException):
class BaseException(object):

Therefore, they cannot be catched with try: ... except Exception as e: (BaseException Documentation).

Solution

Define Exception as the parent class of all Vanna Exceptions instead of BaseException.

Alternative solution

It would be cleaner to have

class VannaError(Exception):
    pass
class ValidationError(VannaError):
    pass

and to only use a try: ... except VannaError as e: block when necessary, but this is not the focus of this PR.

Molrn commented 3 months ago

Chat UI works weird when it executes a SQL with an error

In my opinion this is the most critical issue of this bug. quick fix: override the connect_to_xxxx function of VannaBase like this:

    class MyVanna(VannaBase):
    def connect_to_xxxxxx(self):
        super().connect_to_xxxx()
        run_sql_function = self.run_sql

        def run_sql_with_exception(sql: str) -> DataFrame:
            try:
                return run_sql_function(sql)
            except ValidationError as e:
                raise Exception(e)

        self.run_sql = run_sql_with_exception