Here is the situation. I want all exceptions in doStuff() to bubble up through the code so that they are handled at a higher level.
I'd also like to record how often any exceptions are happening in doStuff() at a higher level as well, and am currently doing this:
begin
doStuff()
rescue Exception =>
raise e, "specific error to log in a db"
doStuff code throw dozens of exceptions, and I want to capture each of these events to put in the db. There is a doStuff2(), which also can throw identical instructions, and I want to know which function they came from.
Adding the additional string, seems to change the exception itself, and I lose all the nice formatting and trace information that the original exception had.
Any suggestions on how I can reraise the original exception, but also keep track of all the exceptions that are occurring within doStuff()?
If you call raise
without passing any argument, Ruby will re-raise the last exception.
begin
doStuff()
rescue => e
log_exception(e)
raise # This will re-raise the last exception.
end
As a side note, I'd like to give you some suggestions about Ruby best practices.
doStuff()
method doesn't follow Ruby naming conventions. You should use underscore for methods. Please use do_stuff
. Also, no need to use ()
if there are no arguments.Exception
class is very low level and it will catch syntax errors as well, and several other compiler issues. You might want to let the application crash in this case so that you are not deploying a broken application.You can save the backtrace and message of the first exception and construct a new exception to raise
begin
rescue Exception => e
new_ex = Exception.new("Error while executing ...:#{e.message}")
new_ex.set_backtrace(e.backtrace)
raise new_ex
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With