how to handle errors like 404 / 500 in rails3

2019-03-20 02:34发布

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!!

3条回答
冷血范
2楼-- · 2019-03-20 02:51

Have a look at this post to redirect all requests causing a Routing Error.

查看更多
仙女界的扛把子
3楼-- · 2019-03-20 02:54

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

查看更多
Fickle 薄情
4楼-- · 2019-03-20 02:55

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)
查看更多
登录 后发表回答