2017-10-11 38 views
0

我有一个代码示例如下:的ActiveRecord :: RecordNotFound样反应处理

def update 
    if @transaction.update(transaction_params) 
    render :show, status: :ok 
    else 
    render json: @transaction.errors, status: :unprocessable_entity 
    end 
end 

当我尝试更新不存在的,换句话说,记录器引发的ActiveRecord :: RecordNotFound。我并不需要抢救和渲染什么,因为这个例外有自己的响应处理什么的,这就是我的回应得到时所提供的无效ID的方法上面,邮递员截图:

enter image description here

这里是文字版:

{ 
    "status": 404, 
    "error": "Not Found", 
    "exception": "#<ActiveRecord::RecordNotFound: Couldn't find Transaction with 'id'=88 [WHERE \"transactions\".\"active\" = ?]>", 
    "traces": { 
     "Application Trace": [ 
      { 
       "id": 6, 
       "trace": "app/controllers/api/v1/transactions_controller.rb:42:in `set_transaction'" 
      } 
     ], 
     "Framework Trace": [ 
      { 
       "id": 0, 
       "trace": "vendor/bundle/gems/activerecord-5.1.4/lib/active_record/relation/finder_methods.rb:343:in `raise_record_not_found_exception!'" 
      }, 
      { 

然而,当我添加自己的控制器类的,我养它从模型中,我得到500,如果我没有具体拯救它,在控制器中。

这是怎么做的ActiveRecord :: RecordNotFound?我如何添加一个响应处理程序到我的自定义错误?

回答

0

我建议你在你的ApplicationController使用rescue_from

class ApplicationController 
    rescue_from MyOwnException do |exception| 
    render 'my_error_view' 
    end 
end 

另外,您可以使用exception_app,在config/application.rb设置这样的:

config.exceptions_app = routes 

然后,您可以控制的渲染通过路线的错误:

match '/404', to: 'exceptions#handle_404' 

您可以在以下博客文章中找到更多详细信息:Handling errors in Ruby on Rails

相关问题