swap.nil swap.nil - 7 months ago 16
Ruby Question

rails rescue_from ScriptError

According to the family tree of Exception.

SyntaxError
is child to
ScriptError


I wish to handle Syntax and/or ScriptError in my rails application.

Exception
NoMemoryError
ScriptError
LoadError
NotImplementedError
SyntaxError
SignalException
Interrupt
StandardError
ArgumentError
IOError
EOFError
IndexError
StopIteration
LocalJumpError
NameError
NoMethodError
RangeError
FloatDomainError
RegexpError
RuntimeError
SecurityError
SystemCallError
SystemStackError
ThreadError
TypeError
ZeroDivisionError
SystemExit
fatal





I did:

rescue_from ScriptError, :with => :notify_on_landing_page


but didn't worked.

Error raised on screen :
SyntaxError in Bc::Muse::User::ProfileController#show


I have created an explicit syntax error, it should gracefully rescue it and do the things I want to.

Answer

Thanks!

I added a middleware to achieve this.

class RescueSyntaxError
  def initialize(app)
    @app = app
  end

  def call(env)
    @app.call(env)
  rescue SyntaxError => error

    request = Rack::Request.new(env)
    session = request.env['rack.session']
    params = request.params

    if session.try(:[], :user_object)
      ##Do validation stuff
      ...
      [302, {'Location' => '/'}, []]
    end
  end
end