views:

421

answers:

2

In Rails.

Exception can rescue in controller class but in model class can not.

How to rescue exception in model?

+2  A: 

Unless I'm mistaken you can use error handling anywhere in Ruby. What are you trying to do?

Andy Gaskell
+7  A: 

You can do exception handling anywhere in a rails application, as it's part of Ruby, not part of Rails. Wherever you want to catch errors, just wrap it as so:

begin
  SomethingElse.doSomething(x, y)
rescue Exception
  ErrorLogger.log(Time.now, "Something went wrong!")
end

Please note that you should always "rescue Exception" instead of just "rescue". Just using "rescue" will only catch StandardError, which is a subclass of Exception (meaning something might get through that you don't want to get through).

Also as usual, you can raise an exception by doing:

raise ArgumentError, "Illegal arguments!"

anywhere in your code, be it a model or controller.

Mike Trpcic
Small correction: You've got a double `raise` in your second code snippet. Good answer though.
Shadwell
That's not a syntax error or double raise. See here: http://web.njit.edu/all_topics/Prog_Lang_Docs/html/ruby/syntax.html#raise
Mike Trpcic
Generally I agree, but I disagree with your first code block.You should not use "rescue Exception" directly since it will rescue even signals that try to kill the process. Unless you're REALLY sure you want to make that portion of code immune to being cleanly killed, stick to the default behavior that Ruby has for a good reason.Thus, it's generally better practice to use a vanilla "rescue" and have your custom error classes derive from StandardError.
nertzy