Rails should display a 404 instead of raising an ActionView::MissingTemplate (HTTP 500)

Why does Rails raises a ActionView::MissingTemplate exception that results in a 500 status code when the requested format is not supported?

For example I get these errors when some bots make random requests to our website:

ActionView::MissingTemplate (Missing template restaurants/page, application/page with {:locale=>[:en], :formats=>[:text], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :jbuilder]}.

If someone makes a request of a webpage with .txt format, and the page only exists in .html format, you should simply return a 404.

Why this behavior of returning a 500? Maybe this should be improved in Rails?

1 Like

This seems to happen when you have a line like this in the controller action:

render :something

If you have only something.html.erb and the request is .txt (for example) you get a 500 status code.

It makes sense. Not being able to render a template doesn’t mean that the requested resource wasn’t found, but that the requested format wasn’t supported. I think this is likely to be a developer facing issue - consumers of your routes will be consuming the formats you support, if you get this error then it’s likely while developing and either misnaming your template or not having added it yet.

Yes, I said 404, but I should have said 406.

406 Not Acceptable” would be the appropriate response, not 500.

Rails makes it easy to respond with a 406 if you prefer. Add a rescue_from clause in your application controller that responds with a :not_acceptable status.

1 Like

Agreed with Matt’s response. I think it’s better for the developer to handle this situation with the response that they fell is appropriate instead of the framework telling you. Having this raise (and thus return a 500) is probably a better callout that something unexpected happened.