繁体   English   中英

如何捕获“错误”:“未定义的方法`[]'为nil:NilClass”

[英]How to catch “error”:“undefined method `[]' for nil:NilClass”

我有一个用于提供Json REST-Api的Rails应用程序。 在我的ApplicationController中,我有这些行来捕获各种错误:

rescue_from ActiveRecord::RecordNotFound,     with: :_404
rescue_from ActiveRecord::RecordInvalid, with: :_400
rescue_from ActiveRecord::RecordNotUnique, with: :_406
....
def _404(exception)
       Rails.logger.error "head 404 with params #{params}"
       render status: 404, :json => {:error => exception.message}
end

在我的一个控制器中,我有一个语句,就像我在不同记录中多次查询数据库一样。

@account = Account.find_by_phone(params[:phone])
@controller = Controller.find_by_controller_id(params[:role_id])
@batlockers_rel = Batlocker.includes(:customer).where("customer_id is not null")

当我打电话给控制器点击特定的动作时,我得到标题和响应正文

 HTTP/1.1 501 NOT IMPLEMENTED
 {"error":"undefined method `[]' for nil:NilClass"}

对于未链接到任何数据库对象的请求参数。 我如何捕获这些NilErrors ,然后如何包含未找到的记录?

可能捕获NameError类或更常见的StandardError:

rescue_from ::NameError, with: :_whatever
rescue_from StandardError, with: :_whatever

但是你需要自己处理这类错误,你需要首次捕获,但你应该解决错误,你的应用程序不应该抛出这种错误,检查数据是否存在于访问元素之前。

暂无
暂无

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

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