felix001
felix001

Reputation: 16691

Logging custom exceptions Python

I have a simple try and except statement. However I want to use logger exception to log the exception. What is the best way of only have 1 line of code for the logger.exception. In the exception base class ?

try:
    do_something()
except CustomBaseExecption, exc:
    logger.exception("Exception Raised:")
    raise GeneralError(exc)
except Exception as exc:
    logger.exception("Exception Raised:")
    raise GeneralError("Unknown Error")

Upvotes: 0

Views: 84

Answers (1)

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23213

Only thing that's changed between two code blocks is GeneralError argument. Let's put a conditional there.

try:
    do_something()
except Exception as exc:
    logger.exception("Exception Raised:")
    raise GeneralError(exc if isinstance(exc, CustomBaseExecption) else "Unknown Error")

Upvotes: 1

Related Questions