Welcome to Working With Rails


Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
Exception error code
3 Posts
Exception error code


When I treat an Exception in my application I do this with the following code:

def x begin ... rescue Exception => e logger.error(e.message) end end

"e.message" gives the error message. Is there a way to get the error code?

Thanks regards

Hi Paulo,

Ruby's base Exception class ( http://www.ruby-doc.org/core/classes/Exception.html ) only has a 'message' property. In cases where a code is needed the original developer will have made a subclass of Exception which defines the extra fields needed.

Your code can have multiple rescue clauses to handle this, for example



rescue SomethingError => er

logger.debug er.code

rescue AnotherException => ex

logger.debug ex.name

rescue Exception => e

logger.debug e.message



When an error occurs, the Ruby interpreter packages the error in an exception object. This object propagates back up the call stack until it reaches some code that explicitly declares it knows how to handle this particular type of exception. Exceptions that are never caught propagate through the call stack, ending up with an abnormal program termination; the stack trace is printed to stderr. This is opposed to returning error codes like shell scripts and C do, leading to less-nested statements, less spaghetti logic and simply better error handling.

Go through this http://www.linuxjournal.com/article/4834

Forum Rating: 100
Sign In To Rate Post
3 Posts
Login to add your message