3

I'm successfully using this technique to programmatically send users to a custom 404 page by raising a RoutingError in a before_action in my controller if there is a problem (e.g. bad params):

before_action :check_invalid_params

def check_invalid_params
    raise ActionController::RoutingError.new('Not Found') if params[:foo].present?
end

This has worked great in my controllers, but I recently tried to DRY up some common error checking into the ApplicationController superclass so that the before_action would be applied to all my controllers.

Unfortunately it seems that if you throw an exception from a before_action callback in ApplicationController, custom error page handling gets short-circuited, and you wind up with a generic 500 error that the middleware generates (like like on this question):

500 Internal Server Error
If you are the administrator of this website, then please read this web application's     
log file and/or the web server's log file to find out what went wrong.

Is there a way to raise an exception from a before_action in ApplicationController and still have custom error page handling? Is there a better way to accomplish this?

Community
  • 1
  • 1
George Armhold
  • 30,824
  • 50
  • 153
  • 232

1 Answers1

1

I would suggest to avoid raise an error if you are able to handle it by checking the params. So for your case I will do this:

def check_invalid_params
  render json:{error: 'foo not found'}, :status => 422 if params[:foo].present?
end

if you call a method that could fail

def some_before_action
  call_external_service
rescue
  render json:{error: 'Internal Server Error'}, :status => 500
end

you can render whatever you want at that point(json is an easy example)

Nan1488
  • 179
  • 2
  • 6