views:

471

answers:

2

I would like to raise an exception so that it does the same thing a normal Rails exception does. Specially, show the exception and stack trace in development mode and show "We're sorry, but something went wrong" page in production mode.

I tried the following:

raise "safety_care group missing!" if group.nil?

But it simply writes "ERROR signing up, group missing!" to the development.log file

+1  A: 

You can do it like this:

class UsersController < ApplicationController
  ## Exception Handling
  class NotActivated < StandardError
  end

  rescue_from NotActivated, :with => :not_activated

  def not_activated(exception)
    flash[:notice] = "This user is not activated."
    Event.new_event "Exception: #{exception.message}", current_user, request.remote_ip
    redirect_to "/"
  end

  def show
      // Do something that fails..
      raise NotActivated unless @user.is_activated?
  end
end

What you're doing here is creating a class "NotActivated" that will serve as Exception. Using raise, you can throw "NotActivated" as an Exception. rescue_from is the way of catching an Exception with a specified method (not_activated in this case). Quite a long example, but it should show you how it works.

Best wishes,
Fabian

halfdan
This does not show the exception and stack trace in development mode and show "We're sorry, but something went wrong" page in production mode.
Chirag Patel
The "we're sorry" page is actually your web server's 500 error handler. Check your .htaccess file and you will usually see it there
Jeff Paquette
+2  A: 

You don't have to do anything special, it should just be working.

When I have a fresh rails app with this controller:

class FooController < ApplicationController
  def index
    raise "error"
  end
end

and go to http://127.0.0.1:3000/foo/

I am seeing the exception with a stack trace.

You might not see the whole stacktrace in the console log because Rails (since 2.3) filters lines from the stack trace that come from the framework itself.

See config/initializers/backtrace_silencers.rb in your Rails project

levinalex