Custom exception with functionality











up vote
1
down vote

favorite












I've encountered a pretty standard issue and was wondering if my solution is the right way to go.



Every time an exception occures I want it to be caught and logged by the caller, and then re-raised.



Since I dont want to repeat logging messages every time, I created a custom exception which saves the message data and also logs.



class LoggingException(Exception):
def __init__(self, message, package_id):
# Get caller informat
caller = getframeinfo(stack()[2][0])
self.filename = caller.filename
self.function = caller.function

# Set message info and log
self.message = message
if (LogManager.log_handler is None):
print(message)
else:
LogManager.l(package_id, LogLevelEnum.ERROR, message)


Use case:



def main_func():
try:
secondary_func()
except Exception as ex:
raise LoggingException("Some log") from ex

def secondary_func():
raise LoggingException("Exception info")


The problem is im not completley sure having an exception do any operations is a good idea, and this to generic for it to not have a standard python solution.



Note: I am not using the python logging module due to product constraints.










share|improve this question
























  • Can you also show an example of how you use this exception? Does this hide the original exception? Also: do you want the code give up when an exception happens?
    – Francesco Montesano
    Nov 11 at 9:58








  • 1




    @FrancescoMontesano Hey, Ive added a use case.
    – Rohi
    Nov 11 at 10:02










  • Do you want your code to output the call stack? It's still unclear to me what you are trying to do - what should someone who catches the exception be able to do/see?
    – kabanus
    Nov 11 at 10:04










  • I'm not sure I understand why this would not be enough... (or this other one one for Py3)
    – Silmathoron
    Nov 11 at 10:10










  • If you have a custom exception that prints out or logs an error message, why do you want to catch it somwhere, and then raise it again? To make the stack trace shorter? Anyway, if you reraise the exception, it will be printed out twice, unless this is what you want. Maybe you don't need to reraise the exception, or, if you need, you should add a parameter to the constructor and not to print the exception second time?
    – VadimK
    Nov 11 at 10:15















up vote
1
down vote

favorite












I've encountered a pretty standard issue and was wondering if my solution is the right way to go.



Every time an exception occures I want it to be caught and logged by the caller, and then re-raised.



Since I dont want to repeat logging messages every time, I created a custom exception which saves the message data and also logs.



class LoggingException(Exception):
def __init__(self, message, package_id):
# Get caller informat
caller = getframeinfo(stack()[2][0])
self.filename = caller.filename
self.function = caller.function

# Set message info and log
self.message = message
if (LogManager.log_handler is None):
print(message)
else:
LogManager.l(package_id, LogLevelEnum.ERROR, message)


Use case:



def main_func():
try:
secondary_func()
except Exception as ex:
raise LoggingException("Some log") from ex

def secondary_func():
raise LoggingException("Exception info")


The problem is im not completley sure having an exception do any operations is a good idea, and this to generic for it to not have a standard python solution.



Note: I am not using the python logging module due to product constraints.










share|improve this question
























  • Can you also show an example of how you use this exception? Does this hide the original exception? Also: do you want the code give up when an exception happens?
    – Francesco Montesano
    Nov 11 at 9:58








  • 1




    @FrancescoMontesano Hey, Ive added a use case.
    – Rohi
    Nov 11 at 10:02










  • Do you want your code to output the call stack? It's still unclear to me what you are trying to do - what should someone who catches the exception be able to do/see?
    – kabanus
    Nov 11 at 10:04










  • I'm not sure I understand why this would not be enough... (or this other one one for Py3)
    – Silmathoron
    Nov 11 at 10:10










  • If you have a custom exception that prints out or logs an error message, why do you want to catch it somwhere, and then raise it again? To make the stack trace shorter? Anyway, if you reraise the exception, it will be printed out twice, unless this is what you want. Maybe you don't need to reraise the exception, or, if you need, you should add a parameter to the constructor and not to print the exception second time?
    – VadimK
    Nov 11 at 10:15













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I've encountered a pretty standard issue and was wondering if my solution is the right way to go.



Every time an exception occures I want it to be caught and logged by the caller, and then re-raised.



Since I dont want to repeat logging messages every time, I created a custom exception which saves the message data and also logs.



class LoggingException(Exception):
def __init__(self, message, package_id):
# Get caller informat
caller = getframeinfo(stack()[2][0])
self.filename = caller.filename
self.function = caller.function

# Set message info and log
self.message = message
if (LogManager.log_handler is None):
print(message)
else:
LogManager.l(package_id, LogLevelEnum.ERROR, message)


Use case:



def main_func():
try:
secondary_func()
except Exception as ex:
raise LoggingException("Some log") from ex

def secondary_func():
raise LoggingException("Exception info")


The problem is im not completley sure having an exception do any operations is a good idea, and this to generic for it to not have a standard python solution.



Note: I am not using the python logging module due to product constraints.










share|improve this question















I've encountered a pretty standard issue and was wondering if my solution is the right way to go.



Every time an exception occures I want it to be caught and logged by the caller, and then re-raised.



Since I dont want to repeat logging messages every time, I created a custom exception which saves the message data and also logs.



class LoggingException(Exception):
def __init__(self, message, package_id):
# Get caller informat
caller = getframeinfo(stack()[2][0])
self.filename = caller.filename
self.function = caller.function

# Set message info and log
self.message = message
if (LogManager.log_handler is None):
print(message)
else:
LogManager.l(package_id, LogLevelEnum.ERROR, message)


Use case:



def main_func():
try:
secondary_func()
except Exception as ex:
raise LoggingException("Some log") from ex

def secondary_func():
raise LoggingException("Exception info")


The problem is im not completley sure having an exception do any operations is a good idea, and this to generic for it to not have a standard python solution.



Note: I am not using the python logging module due to product constraints.







python python-3.x






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 10:18









Mad Physicist

32.3k156694




32.3k156694










asked Nov 11 at 9:50









Rohi

6171321




6171321












  • Can you also show an example of how you use this exception? Does this hide the original exception? Also: do you want the code give up when an exception happens?
    – Francesco Montesano
    Nov 11 at 9:58








  • 1




    @FrancescoMontesano Hey, Ive added a use case.
    – Rohi
    Nov 11 at 10:02










  • Do you want your code to output the call stack? It's still unclear to me what you are trying to do - what should someone who catches the exception be able to do/see?
    – kabanus
    Nov 11 at 10:04










  • I'm not sure I understand why this would not be enough... (or this other one one for Py3)
    – Silmathoron
    Nov 11 at 10:10










  • If you have a custom exception that prints out or logs an error message, why do you want to catch it somwhere, and then raise it again? To make the stack trace shorter? Anyway, if you reraise the exception, it will be printed out twice, unless this is what you want. Maybe you don't need to reraise the exception, or, if you need, you should add a parameter to the constructor and not to print the exception second time?
    – VadimK
    Nov 11 at 10:15


















  • Can you also show an example of how you use this exception? Does this hide the original exception? Also: do you want the code give up when an exception happens?
    – Francesco Montesano
    Nov 11 at 9:58








  • 1




    @FrancescoMontesano Hey, Ive added a use case.
    – Rohi
    Nov 11 at 10:02










  • Do you want your code to output the call stack? It's still unclear to me what you are trying to do - what should someone who catches the exception be able to do/see?
    – kabanus
    Nov 11 at 10:04










  • I'm not sure I understand why this would not be enough... (or this other one one for Py3)
    – Silmathoron
    Nov 11 at 10:10










  • If you have a custom exception that prints out or logs an error message, why do you want to catch it somwhere, and then raise it again? To make the stack trace shorter? Anyway, if you reraise the exception, it will be printed out twice, unless this is what you want. Maybe you don't need to reraise the exception, or, if you need, you should add a parameter to the constructor and not to print the exception second time?
    – VadimK
    Nov 11 at 10:15
















Can you also show an example of how you use this exception? Does this hide the original exception? Also: do you want the code give up when an exception happens?
– Francesco Montesano
Nov 11 at 9:58






Can you also show an example of how you use this exception? Does this hide the original exception? Also: do you want the code give up when an exception happens?
– Francesco Montesano
Nov 11 at 9:58






1




1




@FrancescoMontesano Hey, Ive added a use case.
– Rohi
Nov 11 at 10:02




@FrancescoMontesano Hey, Ive added a use case.
– Rohi
Nov 11 at 10:02












Do you want your code to output the call stack? It's still unclear to me what you are trying to do - what should someone who catches the exception be able to do/see?
– kabanus
Nov 11 at 10:04




Do you want your code to output the call stack? It's still unclear to me what you are trying to do - what should someone who catches the exception be able to do/see?
– kabanus
Nov 11 at 10:04












I'm not sure I understand why this would not be enough... (or this other one one for Py3)
– Silmathoron
Nov 11 at 10:10




I'm not sure I understand why this would not be enough... (or this other one one for Py3)
– Silmathoron
Nov 11 at 10:10












If you have a custom exception that prints out or logs an error message, why do you want to catch it somwhere, and then raise it again? To make the stack trace shorter? Anyway, if you reraise the exception, it will be printed out twice, unless this is what you want. Maybe you don't need to reraise the exception, or, if you need, you should add a parameter to the constructor and not to print the exception second time?
– VadimK
Nov 11 at 10:15




If you have a custom exception that prints out or logs an error message, why do you want to catch it somwhere, and then raise it again? To make the stack trace shorter? Anyway, if you reraise the exception, it will be printed out twice, unless this is what you want. Maybe you don't need to reraise the exception, or, if you need, you should add a parameter to the constructor and not to print the exception second time?
– VadimK
Nov 11 at 10:15












1 Answer
1






active

oldest

votes

















up vote
2
down vote



accepted










Trying to get caller information like that is going to be unreliable. Also, there will be cases where it's not the immediate caller that you are interested in.



The idea of the exception logging itself seems sensible. To compromise, I would move the logging functionality into a separate method that you could trigger explicitly. Exceptions are, after all, mostly regular objects:



class LoggingException(Exception):
def __init__(self, message, package_id):
# Set message info
super.__init__(message)
self.package_id = package_id

def log(self, manager=None):
if manager.log_handler is None:
print(super().__str__())
else:
manager.l(self.package_id, LogLevelEnum.ERROR, super()..__str__())


Now you can trigger the logging operation whenever you want, without having to reconstruct the message:



try:
...
except LoggingException as e:
e.log(some_manager)
raise


This gives you the option of really re-raising the error, as shown here, or chaining it as in your example. I highly recommend against chaining unless you have a really good reason to do it.






share|improve this answer























  • Hey, I liked this solution. The seperation to a log function is probally a good idea, since I want to expand the log, Ill insert self.log() to the init function, and send the extra data.
    – Rohi
    Nov 11 at 11:13











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53247531%2fcustom-exception-with-functionality%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
2
down vote



accepted










Trying to get caller information like that is going to be unreliable. Also, there will be cases where it's not the immediate caller that you are interested in.



The idea of the exception logging itself seems sensible. To compromise, I would move the logging functionality into a separate method that you could trigger explicitly. Exceptions are, after all, mostly regular objects:



class LoggingException(Exception):
def __init__(self, message, package_id):
# Set message info
super.__init__(message)
self.package_id = package_id

def log(self, manager=None):
if manager.log_handler is None:
print(super().__str__())
else:
manager.l(self.package_id, LogLevelEnum.ERROR, super()..__str__())


Now you can trigger the logging operation whenever you want, without having to reconstruct the message:



try:
...
except LoggingException as e:
e.log(some_manager)
raise


This gives you the option of really re-raising the error, as shown here, or chaining it as in your example. I highly recommend against chaining unless you have a really good reason to do it.






share|improve this answer























  • Hey, I liked this solution. The seperation to a log function is probally a good idea, since I want to expand the log, Ill insert self.log() to the init function, and send the extra data.
    – Rohi
    Nov 11 at 11:13















up vote
2
down vote



accepted










Trying to get caller information like that is going to be unreliable. Also, there will be cases where it's not the immediate caller that you are interested in.



The idea of the exception logging itself seems sensible. To compromise, I would move the logging functionality into a separate method that you could trigger explicitly. Exceptions are, after all, mostly regular objects:



class LoggingException(Exception):
def __init__(self, message, package_id):
# Set message info
super.__init__(message)
self.package_id = package_id

def log(self, manager=None):
if manager.log_handler is None:
print(super().__str__())
else:
manager.l(self.package_id, LogLevelEnum.ERROR, super()..__str__())


Now you can trigger the logging operation whenever you want, without having to reconstruct the message:



try:
...
except LoggingException as e:
e.log(some_manager)
raise


This gives you the option of really re-raising the error, as shown here, or chaining it as in your example. I highly recommend against chaining unless you have a really good reason to do it.






share|improve this answer























  • Hey, I liked this solution. The seperation to a log function is probally a good idea, since I want to expand the log, Ill insert self.log() to the init function, and send the extra data.
    – Rohi
    Nov 11 at 11:13













up vote
2
down vote



accepted







up vote
2
down vote



accepted






Trying to get caller information like that is going to be unreliable. Also, there will be cases where it's not the immediate caller that you are interested in.



The idea of the exception logging itself seems sensible. To compromise, I would move the logging functionality into a separate method that you could trigger explicitly. Exceptions are, after all, mostly regular objects:



class LoggingException(Exception):
def __init__(self, message, package_id):
# Set message info
super.__init__(message)
self.package_id = package_id

def log(self, manager=None):
if manager.log_handler is None:
print(super().__str__())
else:
manager.l(self.package_id, LogLevelEnum.ERROR, super()..__str__())


Now you can trigger the logging operation whenever you want, without having to reconstruct the message:



try:
...
except LoggingException as e:
e.log(some_manager)
raise


This gives you the option of really re-raising the error, as shown here, or chaining it as in your example. I highly recommend against chaining unless you have a really good reason to do it.






share|improve this answer














Trying to get caller information like that is going to be unreliable. Also, there will be cases where it's not the immediate caller that you are interested in.



The idea of the exception logging itself seems sensible. To compromise, I would move the logging functionality into a separate method that you could trigger explicitly. Exceptions are, after all, mostly regular objects:



class LoggingException(Exception):
def __init__(self, message, package_id):
# Set message info
super.__init__(message)
self.package_id = package_id

def log(self, manager=None):
if manager.log_handler is None:
print(super().__str__())
else:
manager.l(self.package_id, LogLevelEnum.ERROR, super()..__str__())


Now you can trigger the logging operation whenever you want, without having to reconstruct the message:



try:
...
except LoggingException as e:
e.log(some_manager)
raise


This gives you the option of really re-raising the error, as shown here, or chaining it as in your example. I highly recommend against chaining unless you have a really good reason to do it.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 11 at 10:21

























answered Nov 11 at 10:14









Mad Physicist

32.3k156694




32.3k156694












  • Hey, I liked this solution. The seperation to a log function is probally a good idea, since I want to expand the log, Ill insert self.log() to the init function, and send the extra data.
    – Rohi
    Nov 11 at 11:13


















  • Hey, I liked this solution. The seperation to a log function is probally a good idea, since I want to expand the log, Ill insert self.log() to the init function, and send the extra data.
    – Rohi
    Nov 11 at 11:13
















Hey, I liked this solution. The seperation to a log function is probally a good idea, since I want to expand the log, Ill insert self.log() to the init function, and send the extra data.
– Rohi
Nov 11 at 11:13




Hey, I liked this solution. The seperation to a log function is probally a good idea, since I want to expand the log, Ill insert self.log() to the init function, and send the extra data.
– Rohi
Nov 11 at 11:13


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53247531%2fcustom-exception-with-functionality%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

List item for chat from Array inside array React Native

Thiostrepton

Caerphilly