开发者

Custom error page in Rails for specific actions

开发者 https://www.devze.com 2023-01-29 19:56 出处:网络
I have a controller MyController that some of his actions cannot return full HTML pages but only the content without HTML/HEAD/BODY ...tags.

I have a controller MyController that some of his actions cannot return full HTML pages but only the content without HTML/HEAD/BODY ...tags.

The default error pages are开发者_如何学Go 500.html etc. are indeed full HTML pages and for these MyController:actions I need to somehow get the error pages in a non-full page format.

One way of doing it is:

Override the "render_optional_error_file()" inside the MyController and redirect in case the action is one my special actions to a different version of the error pages (content only, non-full page tags).

Will this work? any other way out there?

BTW: I am working with rails 2.3.9.

Thanks, Erez


It's a bit of a difficult problem, particularly in the case of the 500 error. Since the 500 will render when the application encounters and error, you can't/shouldn't have a dynamic page that is handled by a controller - since this controller could be the source of the problem.

However, in the case of the 404, you could setup an ErrorsController with a 404 action, and use a different layout, depending on whether or not the request was an XHR request or not.

Then all you need is a method in your ApplicationController like:

def render_404
  render "errors/404", :status => 404
end

Which will allow you to call your custom error handler wherever you like.

You could extend this further to add support for the 500 error too (where appropriate) but keep in mind that you will always need the static 500.html in your public folder, incase of a larger problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号