Created
February 22, 2022 07:11
-
-
Save kleontev/7d5767977c20688c9671a1a94934793d to your computer and use it in GitHub Desktop.
helper functions for cx_Oracle exceptions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cx_Oracle | |
from functools import wraps | |
from typing import Optional, Any | |
def is_oracle_exception(e: Exception) -> bool: | |
return isinstance(e, cx_Oracle.Error) | |
def get_ora_error_attr(e: Exception, attr: str) -> Any: | |
if is_oracle_exception(e): | |
error_obj, = e.args | |
return getattr(error_obj, attr) | |
# intentionally returning None, since this | |
# code potentially may be invoked in non-Oracle | |
# exception handlers as well. | |
return None | |
def sqlcode(e: Exception) -> Optional[int]: | |
return get_ora_error_attr(e, 'code') | |
def sqlerrm(e: Exception) -> Optional[str]: | |
return get_ora_error_attr(e, 'message') | |
class suppress_oracle_error: | |
""" | |
Similar to contextlib.suppress, except it suppresses | |
only cx_Oracle errors (either specific ORA-XXXX codes, or | |
all Oracle exceptions). | |
""" | |
def __init__( | |
self, | |
*errors_to_suppress: int, | |
suppress_all_errors=False | |
) -> None: | |
assert errors_to_suppress or suppress_all_errors | |
assert not (suppress_all_errors and errors_to_suppress) | |
self.errors_to_suppress = set(errors_to_suppress) | |
self.suppress_all_errors = suppress_all_errors | |
def __enter__(self): | |
pass | |
def __exit__(self, exc_type, exc_value, tb): | |
if not is_oracle_exception(exc_value): | |
return False | |
if self.suppress_all_errors: | |
return True | |
return sqlcode(exc_value) in self.errors_to_suppress | |
def __call__(self, func): | |
# use as a decorator | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
with self: | |
return func(*args, **kwargs) | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment