Alexander Gorg
Alexander Gorg

Reputation: 1078

Rescue_from is not working

I was trying to handle routing error when I'm loading images and some are missing.

You know I wanted just to replace a missing image with the default image icon and to suppress error message.

So I tried

class ImagesController < ApplicationController
       [...]

       def index
         images = Image.all
         rescue_from ActionController::RoutingError, with: :image_route_error
       end

      [...]
 end

Then I got this:

NoMethodError (undefined method `rescue_from' for #<ImagesController:0x007fe382227e38>
Did you mean?  rescue_handlers):

Any ideas?

Upvotes: 0

Views: 2967

Answers (1)

Pradeep Sapkota
Pradeep Sapkota

Reputation: 2072

You can rescue_from any kind of exceptions other than server errors using rescue_from method. You write this method in your ApplicationController.

rescue_from ActionController::RoutingError do |exception|
    if controller_name == "image" && action_name == "index"
           render 'default_image_here', status: 200 
    else
     render plain: 'Not found', status: 400 
   end
end

In render 'default_image_here' you can use this:

render :text => open(image_url, "rb").read, status: 200

This will read file as binary instead of text.

Upvotes: 2

Related Questions