Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rescue exception in model?

In Rails.

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

How to rescue exception in model?

like image 479
phuwanart Avatar asked Dec 14 '22 02:12

phuwanart


2 Answers

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.

like image 180
Mike Trpcic Avatar answered Dec 26 '22 23:12

Mike Trpcic


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

like image 36
Andy Gaskell Avatar answered Dec 26 '22 22:12

Andy Gaskell