1

I am trying to handle the exceptions/errors generated by Python Snowflake connector.

connection = snowflake.connector.connect(

    user='user',

    password=''password,

    account='account',

    role='ACCOUNTADMIN'

    )

If the connection is successful then it will return a snowflake object or else I would want to handle all the possible exception and print a custom message.

  1. What are the possible exception snowflake.connector.connect method would generate.

  2. How to handle all of those exceptions. (link to the documentation or an example would be really helpful)

1

3 Answers 3

4

If you have a look at the snowflake.connector.errors file you can see a list of all errors that can be returned by the snowflake connector. It doesn't say anywhere about the specific errors that can be returned by snowflake.connector.connect. Here is a list of the error types that I suspect can get returned:

class InterfaceError(Error)
class DatabaseError(Error)
class InternalError(DatabaseError)
class OperationalError(DatabaseError)
class InternalServerError(Error)
class ServiceUnavailableError(Error)
class GatewayTimeoutError(Error)
class ForbiddenError(Error)
class RequestTimeoutError(Error)
class BadRequest(Error)
class BadGatewayError(Error)
class MethodNotAllowed(Error)
class OtherHTTPRetryableError(Error)
class MissingDependencyError(Error)

Rather than trying to handle every error, you should only handle the errors that you know what to do with. For example, you wouldn't handle an InternalServerError unless you knew what to do to fix it. Instead, log it and let it fail.

Here is an example of how you would catch a bad username/password. You could then ask the user to re-enter their details:

import os
import snowflake.connector
from snowflake.connector.errors import DatabaseError, ProgrammingError

snowflake_account = os.environ['SNOWFLAKE_ACCOUNT']

if __name__ == '__main__':
    try:
        con = snowflake.connector.connect(
            user='bad username',       # <-------- Bad user
            password='bad password',   # <-------- Bad pass
            account=snowflake_account  # <-------- This is correct
        )
    except DatabaseError as db_ex:
        if db_ex.errno == 250001:
            print(f"Invalid username/password, please re-enter username and password...")
            # code for user to re-enter username & pass
        else:
            raise
    except Exception as ex:
        # Log this
        print(f"Some error you don't know how to handle {ex}")
        raise
    else:
        try:
            results = con.cursor().execute("select * from db.schema.table").fetchall()
            print(results)
        except ProgrammingError as db_ex:
            print(f"Programming error: {db_ex}")
            raise
        finally:
            con.close()

I've also put in an example of catching a ProgrammingError which can be raised when you enter some invalid SQL.

Sign up to request clarification or add additional context in comments.

2 Comments

hello @SimonD : you have any good blog for logging with snowflake.. ?
Not off the top of my head @PIG. I'd just be googling, unfortunately.
1

You can use try.. catch method in python

    try:
        self.mainsfconnection = sf.connect(
        user=config.user,
        password=config.password,
        account=config.account,
        warehouse=config.warehouse,
        role=config.role,
        database=config.database,
        schema=config.schema)

        # -- Snowflake : Default Session parameters
        self.mainsfconnection.cursor().execute("USE ROLE {0}".format(config.role))
        self.mainsfconnection.cursor().execute("USE WAREHOUSE {0}".format(config.warehouse))
        self.mainsfconnection.cursor().execute("USE SCHEMA {0}.{1}".format(config.database, config.schema))

    # -- Exception clause : snowflake
    except sf.errors.ProgrammingError as e:
        print('SQL Execu tion Error: {0}'.format(e.msg))
        print('Snowflake Query Id: {0}'.format(e.sfqid))
        print('Error Number: {0}'.format(e.errno))
        print('SQL State: {0}'.format(e.sqlstate))

Comments

-1

Here's a really good example from the docs, note there is no reason not to move the cur = and the connection = to below the try command (with proper indentation of course):

https://docs.snowflake.com/en/user-guide/python-connector-example.html#handling-errors

# Catching the syntax error
cur = con.cursor()
try:
    cur.execute("SELECT * FROM testtable")
except snowflake.connector.errors.ProgrammingError as e:
    # default error message
    print(e)
    # customer error message
    print('Error {0} ({1}): {2} ({3})'.format(e.errno, e.sqlstate, e.msg, e.sfqid))
finally:
    cur.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.