ruby-on-rails - 为什么 ActiveRecord::StatementInvalid 在这个 Rails 方法中无法拯救?

标签 ruby-on-rails exception activerecord rescue

为什么我无法用以下方法挽救任何东西?

def get_things
  begin
    things= @member.things.where("id>?",params[:id])
  rescue ActiveRecord::StatementInvalid
    render( inline: "RESCUED ActiveRecord::StatementInvalid" )
    return
  rescue
    render( inline: "RESCUED something" )
    return
  end
  render( inline: "#{things.first.title}" )
end

当使用有效 id 调用时,它可以工作:
$  curl -vd "id=3" http://localhost:3000/get_things

但是如果我通过了一个错误的,例如:
$  curl -vd "id=3,0" http://localhost:3000/get_things
$  curl -vd "id='3'" http://localhost:3000/get_things

异常未获救:
< HTTP/1.1 500 Internal Server Error
<h1>
  ActiveRecord::StatementInvalid
    in ApplicationController#get_things
</h1>
<pre>PG::Error: ERROR:  invalid input syntax for integer: &quot;'3'&quot;

仅当渲染发生在开始/救援块内时
def get_things
  begin
    things= @member.things.where("id>?",params[:id])
    render( inline: "#{things.first.title}" )
  rescue ActiveRecord::StatementInvalid
    render( inline: "RESCUED ActiveRecord::StatementInvalid" )
    return
  end
end

它按预期工作:
$ curl -vd "id='3'" http://localhost:3000/get_things
  < HTTP/1.1 200 OK
  RESCUED ActiveRecord::StatementInvalid

最佳答案

据我所知,things在您的情况下,将是一个包含查询信息的类,但在您尝试访问基于查询的元素(如 things.first )之前,不会执行查询。

things= @member.things.where("id>?",params[:id]) # query not run
things= things.order("id desc") # still not run
things.first.title # now the query runs, the statement can be invalid

这就是它不能被拯救的原因,因为在你的渲染行中,异常发生的地方,而不是在 things 的创建中。 .

这应该没问题:
def get_things
  begin
    things= @member.things.where("id>?",params[:id])
    thing_title = things.first.title
  rescue ActiveRecord::StatementInvalid
    render( inline: "RESCUED ActiveRecord::StatementInvalid" )
    return
  rescue
    render( inline: "RESCUED something" )
    return
  end
  render( inline: "#{thing_title}" )
end

关于ruby-on-rails - 为什么 ActiveRecord::StatementInvalid 在这个 Rails 方法中无法拯救?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11483973/

相关文章:

ruby-on-rails - Rails 控制台 : Run a Ruby file several times

ruby-on-rails - Rails 性能分析器

C++ 异常和 ld 符号警告

mysql - activerecord 3.2.2 与多个连接的关联问题

ruby-on-rails - 非持久关联条件下的Rails

ruby-on-rails - Rails 3 将文本制作为可点击的链接

ruby-on-rails - Rails 日志中的 "object allocation during garbage collection phase"是什么意思?

java - 我如何处理用户定义的异常并在处理它们后恢复程序流程

c# - 为什么我不能使用反射加载 AssemblyVersion 属性?

ruby-on-rails - 在 Rails 中查找自引用关系中的后代