Home > Blockchain >  ActionController::UnknownFormat with image HTTP_ACCEPT (Ruby on Rails)
ActionController::UnknownFormat with image HTTP_ACCEPT (Ruby on Rails)

Time:02-21

Website suddenly started throwing a massive ActionController::UnknownFormat exceptions. There seem to be a lot of image/* requests. But the function is not supposed to handle such kind of requests and it gives ActionController::UnknownFormat error. It manages only HTML and JS requests.

what is the best way in Ruby on Rails to manage these requests, and how we can avoid such kind of unwanted requests without giving errors.

enter image description here

enter image description here

Here is a sample code:

if params[:verification_token].present?
  setup_verification
end 
@participants = ProjectParticipant.includes(:business_activities, :employments, company: :logo).awarded.where(project_id: @project.id)
@company_participation = @participants.where(company_id: @company.id).first
@project_participants = @participants.where.not(company_id: @company.id)


    q = ERB::Util.url_encode(@project.title)

    @response = JSON.parse(get_articles("https://www.googleapis.com/customsearch/v1?q=#{q}&exactTerms=#{q}&start=1&cx=#{ENV['CUSTOM_SEARCH_IDENTIFIER']}&key=#{ENV['GOOGLE_API_KEY']}&sort=date"))
    track_analytics_event if @project

    respond_to do |format|
      format.html # show.html.erb
      format.js
    end

I'm using ruby 2.5 with rails 5.1.6.

CodePudding user response:

One way to handle these requests is by adding format constraints on your routes in config/routes.rb. For example,

get 'foo' => "application#bar", constraints: lambda { |req| req.format == :js || req.format == :html }

will only route 'foo' requests with accept type js/html to the 'application#bar' action. Requests with other accept types will get a 404 response.

Another option is to handle these errors within the controller. Something like this

rescue_from ActionController::UnknownFormat, with: :unknown_format_error

def unknown_format_error
  render(text: 'Unknown format.', status: :not_found)
end

This way gives you the ability to customize the response.

  • Related