views:

40

answers:

2

how do i display error messages in the web browser when using rails?

eg. if i use a variable in the view that i hasn't defined in the controller i want to get an error message.

thanks

+1  A: 

In your controller:

def your_method
  #processing that fails
  flash[:notice] = 'your error message'
end

In your view:

<% if !flash[:notice].nil? %>
    <p id="notice"><%= flash[:notice] %></p>
<% end %>

The documentation for the Flash hash is available here.

To rescue from errors at the application level rather than displaying error messages to the user, you can use

  rescue_from ErrorType, :with => :action_method

Examples:
http://stackoverflow.com/questions/101012/customising-the-generic-rails-error-message
http://www.perfectline.co.uk/blog/custom-dynamic-error-pages-in-ruby-on-rails

Jim Schubert
i meant more like errors that is generated by rails (maybe the view is using a variable that hasnt been defined)
never_had_a_name
fayer. Thanks for the accept even though I didn't answer the question you were looking for. Your question was short and made it sound like a per-controller exception should be displayed as an error message. I updated my answer with a couple of references for how to show a customized error page based on exceptions in your controllers. The second link is a pretty good resource and shows how to catch errors and log, but you'll have to be careful that logging doesn't throw errors or you'll get locked in a loop.
Jim Schubert
A: 

When you have errors like the mentioned one, when you try to reach the respective page you should have an error message instead of the proper page.

dombesz