Intermittent Ruby on Rails log (ActionView::MissingTemplate) - ruby-on-rails

I keep seeing errors in my logs similar to the below.
Can anyone suggest why I could be getting such an error intermittently? Is it a caching issue?
Every time I attempt to load the about-us page it loads perfectly but every few days there's an error like this in my logs but it's not confined to a single page. Sometimes it's the homepage, some times it's other pages.
Started GET "/about-us" for xxx.xxx.xxx.xxx at 2014-08-16 07:54:06 +0100
Processing by PagesController#about as */*;q=0.6
Geokit is using the domain: mydomain.com
[1m[35mPage Load (0.2ms)[0m SELECT `pages`.* FROM `pages` WHERE `pages`.`name` = 'About Us' LIMIT 1
Completed 500 Internal Server Error in 2ms
ActionView::MissingTemplate (Missing template pages/about, application/about with {:handlers=>[:erb, :builder, :arb], :formats=>["*/*;q=0.6"], :locale=>[:en, :en]}. Searched in:
* "/var/www/myapp/releases/201408150651/app/views"
* "/var/lib/ruby-rvm/gems/ruby-1.9.2-p320/gems/activeadmin-0.3.2/app/views"
* "/var/lib/ruby-rvm/gems/ruby-1.9.2-p320/gems/kaminari-0.12.4/app/views"
* "/var/lib/ruby-rvm/gems/ruby-1.9.2-p320/gems/devise-1.4.7/app/views"
):
This question is similar to: Random rails ActionView::MissingTemplate errors so this is happening to other people but there's no defined answer there either.

You can't prevent this error as there are load reasons(like you mentioned missing cache, unknown request format and etc)
You can try to restrict the number of predefined formats like:
get '/about-us' => 'controller#about', :format => /(?:|html|json)/
Also you can suppress this exception. Create a new file(for example exception_handler.rb) in the directory config/initializers and Add this line into created file:
ActionDispatch::ExceptionWrapper.rescue_responses.merge! 'ActionView::MissingTemplate' => :not_found
Hope it helps.

#ProblemSolvers is a possible solution. However, I added the following method in my application_controller.rb file so that such errors will render a 404 page rather failing with a error message on screen
rescue_from ActionView::MissingTemplate, :with => :rescue_not_found
protected
def rescue_not_found
Rails.logger.warn "Redirect to 404, Error: ActionView::MissingTemplate"
redirect_to '/404' #or your 404 page
end
you can wrap this code in a if statement, something like this if Rails.env.production? given that the env is setup so your dev environment wont be affected

Related

Can't catch ActiveRecord::RecordNotFound with rescue

I'm new to Ruby, please bear with me if this is a stupid question, or if I'm not following the best practice.
I'm finding an object in the DB using find(), and expect it to throw RecordNotFound in case the object of the id does not exist, like this.
begin
event = Event.find(event_id)
rescue ActiveRecord::RecordNotFound => e
Rails.logger.debug "Event does not exist, id: " + event_id
return {
# return "unauthorized" to avoid testing existence of event id
# (some redacted codes)
}
end
But somehow it is not caught (the log in the rescue block is not printed) and the entire program just return internal server error. Here's the stack trace:
Completed 500 Internal Server Error in 22ms (ActiveRecord: 1.0ms)
ActiveRecord::RecordNotFound (Couldn't find Event with 'id'=999):
lib/sync/create_update_event_handler.rb:78:in `handleRequest'
app/controllers/sync_controller.rb:36:in `block in sync'
app/controllers/sync_controller.rb:31:in `each'
app/controllers/sync_controller.rb:31:in `sync'
Rendering /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
Rendering /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
Rendered /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (6.4ms)
Rendering /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
Rendered /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.3ms)
Rendering /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
Rendered /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.9ms)
Rendered /usr/local/rvm/gems/ruby-2.4.0/gems/actionpack-5.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (36.6ms)
The only thing I can think of is there are two different ActiveRecord::RecordNotFound, and I'm catching the wrong one, but I don't know if it is the case or how I can verify it.
What did I do wrong?
======================================
Update
The problem is in the rescue block, I was concatenating event_id (an integer) to a string.
The RecordNotFound exception was indeed caught, but when the type error was thrown in the rescue block, the wrong error message was printed.
You won't get an error if you do
event = Event.find_by(id: event_id)
In this case if the record can't be found by ID it will just event == nil be nil.
In this case if the record can't be found by ID it will just event == nil be nil.
The code you pasted works fine for me. If you don't see output in the log, check your environment and log level settings INFO, WARN, DEBUG etc. 500 error indicates some kind of controller action raising the error.
see Set logging levels in Ruby on Rails
To be sure your rescue block is executing try doing something besides log. If you're running a development server you can try :
begin
event = Event.find(event_id)
rescue ActiveRecord::RecordNotFound => e
msg = "Event does not exist, id: #{event_id.to_s}"
Rails.logger.debug msg.
puts msg
binding.pry # if you have gem 'pry' in your development gems.
File.open('test.log', 'w') {|f| f.write msg} #check if this appears in root of your app
return {
# return "unauthorized" to avoid testing existence of event id
# (some redacted codes)
}
end
UPDATE: I changed the string interpolation according to your answer. You can also call .to_s inside interpolation instead of closing quotes and appending.
Turned out the error message is wrong.
The problem is that I was concentating the event_id (an integer) to a string.
But somehow Rails prints out the RecordNotFound exception.
The problem is fixed by replacing
Rails.logger.debug "Event does not exist, id: " + event_id
with
Rails.logger.debug "Event does not exist, id: " + event_id.to_s
Thanks #lacostenycoder for bringing my attention to the error message.
#event = Event.find(params[:id]). you should write instead params[:id] .That's the cause of an error.

rails4 // ActionController::UnknownFormat

Some bots or other external requests cause an ActionController::UnknownFormat error when redirecting
Is there a catch-all method to add somewhere in application_controller to handle those errors ?
A config spec to add a default method in request (if none specified) ?
Below an example of trace :
An ActionController::UnknownFormat occurred in main#index:
ActionController::UnknownFormat
app/controllers/main_controller.rb:17:in `index'
-------------------------------
Request:
-------------------------------
* URL : http://ownedurl.com/
* HTTP Method: GET
* IP address : 82.xxx.xxx.xxx
* Parameters : {"controller"=>"main", "action"=>"index"}
* Timestamp : 2015-06-07 20:54:32 +0200
* Server : servername
* Rails root : /var/www/ownedurl.com/releases/208
* Process: 29726
A get request would obviously work; yet it makes it occurs.
Experiences on this one appreciated
thx a lot
This will handle a request without format :
rescue_from ActionController::UnknownFormat, with: :raise_not_found
def raise_not_found
render(text: 'Not Found', status: 404)
end
You can supply the :format to your routes itself to tell it what are the formats are valid and which are not.
Read some discussions on this and this answer.

NoMethodError users_url with devise (ajax)

I use devise 2.2.2 with rails 3.2.11
I use devise with ajax requests
I changed the following configuration in initializers/devise.rb
config.navigational_formats = [:json, :html]
config.http_authenticatable_on_xhr = false
when I submit an empty sign in request, I expect to get a json response with errors hash, but i get a 500 instead (see below for the trace) (it works fine with sign up request)
here are my routes (nothing special)
devise_for :users
the trace:
Started POST "/users/sign_in.json" for 127.0.0.1 at 2013-01-27 13:33:45 +0100
Processing by Devise::SessionsController#create as JSON
Parameters: {"user"=>{"email"=>"", "password"=>"[FILTERED]"}}
Completed 401 Unauthorized in 1ms
Processing by Devise::SessionsController#new as JSON
Parameters: {"user"=>{"email"=>"", "password"=>"[FILTERED]"}}
Completed 500 Internal Server Error in 40ms
NoMethodError (undefined method `users_url' for #<Devise::SessionsController:0x007fe88ddd9550>):
You are probably overriding after_sign_in_path_for and have a code path in there that returns nil.
This causes devise to fall back to its default behaviour and call users_url to get the path to redirect to.
Why do I think this? Because you are having the same error I had (and lost some hair over) and also this bug report contains the github usernames of many other people who have been humbled by this particular issue.

Rails still throwing error for page that doesn't exist?

I used to have a class Uploads that I later decided to delete. I ran a migration to drop the table, made sure my schema was updated, manually deleted the associated views and controllers, etc. I even ran a grep through my directory to check for traces of "upload" or references to it. However, when I try to access my page I get an error in the console -- 500 Service Error. the log says:
ActionView::MissingTemplate (Missing template /app\views\upload\uploadfile.rhtml with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. Searched in:
* "/Users/claire/Documents/folio/app/views"
* "/Users/claire/Documents/folio"
* "/"
):
app/controllers/upload_controller.rb:3:in `index'
...But neither of those documents exist anymore. I tried clearing my cache and cookies an it has the same effect. What could be causing this?!
My routes.rb file
Folio::Application.routes.draw do
resources :projects
#get "home/index"
root :to => "projects#new"
match 'project/new',:controller=>"projects",:action=>"create"
match "project/:id", :controller => "projects", :action=>"download"
match "projects_controller/filter_list", :controller => "projects", :action => "filter_list"
end
Can you post your routes file? I think the problem is that you still have routes pointing to the deleted controller.

Rails route hanging

I'm trying to get someone else's app up and running on my development laptop but I ran into a routing issue and I'm not sure how to debug it. For a particular controller/action, it just hangs and doesn't time out and there is no error message in the development log. Does anyone know how I can debug this? Thanks.
Edited per comments.
config.rb
ActionController::Routing::Routes.draw do |map|
map.signup "/signup", :controller => "business_accounts", :action => "new"
map.resources :beta_signups, :controller => 'public/beta_signups'
map.root :controller => "public/pages", :action => "index"
end
For brevity, I commented out the rest of the routes and left in a couple of routes that work. The one that failed is the signup route, it simply hangs and never times out.
Here's are the relevant output from the development.log showing a route that works (root) and one that doesn't (signup)
Parameters: {"action"=>"index", "controller"=>"public/pages"}
Rendering template within layouts/public
Rendering public/pages/index
Completed in 672ms (View: 656, DB: 15) | 200 OK [http://localhost/]
SQL (0.0ms) SET client_min_messages TO 'panic'
SQL (0.0ms) SET client_min_messages TO 'notice'
Processing BusinessAccountsController#new (for 127.0.0.1 at 2010-04-22 10:01:30)
[GET]
Parameters: {"action"=>"new", "controller"=>"business_accounts"}
Not sure if this makes any difference but it is running on thin and bundler.
Stripped the controller down to the bare minimum and still getting the same error
class BusinessAccountsController < SSLController
def new
logger.debug "here"
end
end
And I just noticed SSLController, hmm, I need to look into that.
Son of a !#%$##%$%!$#!%, SSLController was my problem, there is no SSL setup on my laptop and the net effect is the app hanging with no error message. Changing it to ApplicationController works. Thanks #Taryn, it was your request that made me looked closer at the code, funny how I've looked at it for days and never saw it till now.

Resources