Catch an ActionMailer exception?

Hi,

I’ve got actionmailer set to raise an error on failure. When a user
submits my contact form, and they use a bogus address ‘[email protected]’, then
the following error occurs in the production.log:

Net::SMTPFatalError (553 5.1.8 Sender address [email protected] domain does not
exist)

What I would like to do is catch the error, add the message to the
errors for the email address field, and redisplay the form.

I’m sure that ruby/rails can somehow catch the error, probably with some
sort of rescue. I couldn’t find much in the way of reference to how to
use the rescue handling on rails. Are there any docs for this, beyond
just the rdoc?

Here is my existing action:
def contact
@contact = Contact.new
if request.post?
@contact.attributes = params[:contact]
if @contact.valid?
email = UserNotifier.create_contact_request(@contact)
UserNotifier.deliver(email)
render(:text => ‘

Thank you for your
comment or question. Our staff will reply as soon as possible.

’,
:layout => ‘/layouts/application.rhtml’)
end
else
if logged_in?
@contact.name = current_user.fullname
@contact.telephone = current_user.telephone
@contact.email = current_user.email
end
end
end

Thanks!

Regards,
Rich

It gives you the name of the error class, so trapping should be fairly
simple.

def contact
data = params[:data]

begin
  Mailer.deliver_some_email(data)
rescue Net::SMTPFatalError => e
  if e.to_s.include?('domain does not exist')
    render :text => 'Enter a real email dummy!'
  else
    raise e
  end
end

end

This should catch the Net::SMTPFatalError when its thrown by the mailer
deliver method. I’m not it’s necesary but I test the error message to
see if it contains the non existent domain message because
SMTPFatalError sounds awfully ambiguous. You dont want to tell the user
it was a bad domain name unless that is really the case. If the error
is not what expect then re-raise the error. This may be unecesary if
this is the only thing Net::SMTPFatalError is used for.

Alternatively you can do something like:

def contact
Mailer.deliver_some_email(data)
rescue Net::SMTPFatalError
render :text => ‘Enter a real email dummy!’
end

I left out the above error validation, but in a simple action it shows
simpler way to trap any error in the entire method rather than just a
code chunk.