'Custom Exception to catch Specific Connection Error
I have tried to follow a few similar questions, but could not find a suitable answer for my use-case. I am using a jdbc connector to link to a database. However since the exception errors don't match any of the readily available ones through python I want to create a custom one exception based on the output message of the error. Below is my class for the connection
class JBconn(object):
"""Function class for the database connection.
Args:
username(str): user id
password (str): Password
JAR_PATH(str): relative path to the Jar file
Returns:
connection object to the database
"""
@classmethod
def get_connection(cls, username, password, JAR_PATH):
jHome = jpype.getDefaultJVMPath()
jpype.startJVM(
jHome,
"-Djava.class.path=" + JAR_PATH,
"-Doracle.jdbc.timezoneAsRegion=false",
)
try:
conn = jaydebeapi.connect(
"com.osisoft.jdbc.Driver",
"jdbc:pioledb://mydummysite.com/Data Source=MyDummy.com",
[username, password],
)
return conn
except JDBConnectionError as e:
logger.error("Below is the error in connection" + "\n")
logger.error(str(e) + "\n")
return None
What I am trying to employ utilizes the following logic: The class will accept the error message and if it contains the string '403 Forbidden' then it will return the message "Connection to database was refused". Below is my attempt at defining this exception class:
class CustomExceptions(Exception):
pass
class JDBConnectionError(CustomExceptions):
def __init__(self, msg):
self.message = msg
def __str__(self):
if self.message.find("403 Forbidden") != 1:
return "Connection to PI was refused"
When I ran this code it didn't work. The exception was never caught.
What would be the correct way to implement this idea? How do I pass in the message of the error as the class argument?
Any help is greatly appreciated. Thank 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 |
|---|
