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 :)
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.
duplicate of this
however you should rescue in this way
def update
@game = Game.find(params[:id])
begin
params[:game][:tier] = eval(params[:game][:tier])
rescue Exception => e
@game.errors.add(:tier, "Please make sure the correct format for tier, example [100, 1000, 10000]")
end
#.... more code
end
in order to make it work
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.