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
Exception handling in Ruby on Rails is similar to exception handling in Ruby. Which means, we enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.
except is how you handle an exception that some other code signalled. raise is how you signal an exception yourself. It's like asking what the difference is between making a phone call and answering the phone. In except you usually handle exceptions, you normally don't raise other exceptions.
Ruby actually gives you the power to manually raise exceptions yourself by calling Kernel#raise. This allows you to choose what type of exception to raise and even set your own error message. If you do not specify what type of exception to raise, Ruby will default to RuntimeError (a subclass of StandardError ).
When an exception is raised, no further statements in the current block of code are executed.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With