简体   繁体   English

开始和救援块异常处理

[英]Begin and Rescue block exception handling

I have little experience in rails exception handling. 我在Rails异常处理方面经验很少。 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. 万一params [:game] [:tier] =“ [100,200]”一切就完美了。 In case of error case of ruby syntax like params[:game][:tier] = "[100,200] abc" it catch the error however the application just crush. 如果发生红宝石语法错误,例如params [:game] [:tier] =“ [100,200] abc”,它会捕获错误,但是应用程序会崩溃。

How can I handle exception with 'eval()' such that it won't crush the app? 我该如何使用'eval()'处理异常,以免破坏应用程序? 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 /')" ? 如果params[:game][:tier]"[100,200]; system('rm -rf /')"怎么办?

Since the incoming data is expected to be an array, I would not use eval but JSON.parse instead: 由于预期传入数据是一个数组,因此我不使用eval而是JSON.parse

> 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 然后仅从JSON::ParserError异常进行救援

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 为了使它起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM