Rails:捕获无效SQL查询的异常



如果用户愿意,我允许他以高级形式输入自定义SQL查询,并且我将他的输入直接提供给我的搜索方法中的"where"子句。

当然,有时用户会输入无效的SQL查询。现在,这会导致出现一个错误页面。我希望它显示一个"invalid syntax"语句。

def self.search(search)
    if search
        begin 
          includes(:hobbies, :games).where(search)
        rescue SQL_syntax_error_exception # ?
          #display error message
        end

我对此感到困惑,因为即使我尝试了(据说)包含所有内容的

rescue => e

我肯定会不建议这样做——您将很难在没有引号的情况下对整个where子句进行消毒。

对于捕获错误,

begin
  includes(:hobbies, :games).where(search)
rescue ActiveRecord::StatementInvalid => e
  # do whatever
end

注意,这里可能会发生一些异常(不仅仅是ActiveRecord::StatementInvalid),所以你可能想做一些像:

  ...
rescue Exception => e
  if e.class.ancestors.include? ActiveRecord::ActiveRecordError
    # rescue stuff
  else
    # re-throw the exception
  end
end 

最新更新