简体   繁体   中英

ActiveRecord::RecordNotFound like response handling

I have a code example like this :

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

And when I try to update record which does not exist, in other words controller raises ActiveRecord::RecordNotFound. I don't need to rescue and render anything, as this exception has its own response handler or something, this is what I get in the response when provided invalid id to the method above, postman screenshot:

在此处输入图片说明

Here is text version:

{
    "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!'"
            },
            {

However when I add my own controller class, and I raise it from the model, I get 500 if I don't specifically rescue it, in the controller.

How is this done for ActiveRecord::RecordNotFound? How can I add a response handler to my custom error?

I would suggest you use rescue_from in your ApplicationController:

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

Alternatively you could use the exception_app, setting it like this in config/application.rb :

config.exceptions_app = routes

You can then control the rendering of the errors through the routes:

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

You can find more details on this blog post: Handling errors in Ruby on Rails

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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