sameera207
sameera207

Reputation: 16619

Low-level exception handling in Rails

How can I use exception handling in Rails? Currently I have done following.

In each controller method I have added

begin
  <myCode>
rescue
  <exception handler>

But I think with Rails I should be able to define an exception handler method in Application controller and catch all the exceptions from there, without handling them from each method.

I have used 'rescue_action_in_public' in my application controller, but when I given a wrong database name in config/database.yml and load the application, it doesn't catch those exceptions.

My questions are

1 - Is it a recompilation practice to have one exception handler in the application controller and catch the exceptions ? If not, what is the standard way ?

2 - How can I handle the Exceptions like Databse not found, doesn't have permission to view table fields, etc kind of low level exceptions

I'm riding on Rails 3 and I have some projects in Rails 2.3.8 as well

Upvotes: 1

Views: 661

Answers (2)

Rx.
Rx.

Reputation: 1

For Rails 3 you can use rescue_from in your ApplicationController. If the exceptions you want to catch are at a lower level then you can configure a Rack Middleware layer will allow you to catch exceptions that the controller does not have access to. This is how Hoptoad works. I recently released a rails 3 gem that will catch common exceptions using rescue_from and provide well defined http status codes and error responses for html, json and xml. This may or may not fit your needs. https://github.com/voomify/egregious

Upvotes: 0

Anatoly
Anatoly

Reputation: 15530

With according to Advanced Rails Recipes book by PragProg, the general exception handling is the good approach. rescue_action (all environments), and rescue_action_in_public (production) are using to caught any exceptions in abstract controller class. So you do it right way.

Boot application happens before the controllers are loaded, so you can't handle database.yml over there. If you still need to do it, put an initializer ruby file to check that the file exist and a valid, then initialize AR::Base connection to perform DESC table for instance.

Upvotes: 1

Related Questions