Sunday, 18 April 2010

Rails observers and exception handling

I can't find much written about this, so here goes.

If you have  a Rails observer watching a model for a new account being created, and sending an email, that process could potentially generate errors, which you may wish to trap - say if the email address is user entered, and is undeliverable.  You could do that with begin..rescue..end, and that may be fine - it will prevent the user from just being presented with a 500.

However, what if you actually need to do something with the error - given that observers are essentially models, you can't even set a flash from them

After much experimentation, it seems to me that the best way to do this is to insert a rescue_from at the top of the controller concerned.  Something like:

    rescue_from Net::SMTPFatalError do
        flash[:error] = "Please check the email address."
        render 'show'
    end
Note that the render is essential - the server throws a rather bizarre 500 (can't convert array to string) otherwise.  No idea why.

No comments:

Post a Comment