Ruby-on-rails – Begin and Rescue block exception handling

exception handlingrubyruby-on-rails

I have little experience in rails exception handling. I have this snippet

def update
  @game = Game.find(params[:id])
  begin
    params[:game][:tier] = eval(params[:game][:tier]) 
  rescue 
    @game.errors.add(:tier, "Please make sure the correct format for tier, example [100, 1000, 10000]")
  end
#.... more code
end

In case params[:game][:tier] = "[100,200]" everything is perfect.
In case of error case of ruby syntax like params[:game][:tier] = "[100,200] abc" it catch the error however the application just crush.

How can I handle exception with 'eval()' such that it won't crush the app? Why begin and rescue does not work in this case? Appreciate any help for ruby enlightenment thanks 🙂

Best Answer

What if params[:game][:tier] was "[100,200]; system('rm -rf /')"?

Since the incoming data is expected to be an array, I would not use eval but JSON.parse instead:

> JSON.parse("[100,200]")
 => [100, 200]
> JSON.parse("[100,200] abc")
JSON::ParserError: 746: unexpected token at 'abc'...

Then rescue from only a JSON::ParserError exception

rescue JSON::ParserError => e

This will also solve the rescue not catching the exception problem you're having.