Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle errors like 404 / 500 in rails3

Hey, I hope you can help me.

I am trying to find a way to direct the user to the default error pages 404.html and 500.html in my public folder.

So when there is a routing or nomethod error it should be directed there to. I already tried some stuff in my application controller but it didnt work.

Many thanks!!

like image 741
daniel Avatar asked Jan 09 '11 17:01

daniel


2 Answers

Rails does this for you automatically when running in production mode. When you upload your application to a live server, Rails takes care of handling those exceptions and rendering the correct error pages with the correct header status. If you're trying to see what those pages look like (for testing or something), just access them directly via http://localhost:3000/404.html

Whenever you set up your Rails application on a live server (let's use Apache as an example), you give the site root as the /public folder in your application. Then, whenever a request is made to that server address, Apache first looks in that public folder and tries to serve a static asset (this is a configurable option in [environment].rb). If it can't find the requested page, then the request is forwarded through the Ruby stack.

When in production mode, if Rails encounters an error that isn't handled (i.e begin, rescue), it throws the error the whole way up to the stack, which then tells Apache (again, in my example) to render an appropriate error.

Here are some common errors that you'll see in development mode and what they render in production mode:

ActiveRecord::RecordNotFound => 404 (page not found)
nil.method => 500 (server error) unless you turn off whiny nils
ActionController::RoutingError => 404 (page not found)
like image 111
sethvargo Avatar answered Dec 24 '22 21:12

sethvargo


Happens automatically if run in production mode - no need that you do that manually.

like image 41
Marcel Jackwerth Avatar answered Dec 24 '22 20:12

Marcel Jackwerth