Incerteza
Incerteza

Reputation: 34884

Handling an exception in an ajax action

I have an ajax action in Rails:

def ajax_action1
    begin
      item = Model1.where(id: params[:id]).first
      if item
       #....
      else
        render json: { errors: ['Not found'] }, status: 404
      end
    rescue
      render json: { errors: ['Unexpected exception, try again later.'] }, status: 503
    end
  end

I wonder, is it sensible enough to have an action like this? Is there they better way of doing this out there?

Upvotes: 0

Views: 265

Answers (1)

Roman Kiselenko
Roman Kiselenko

Reputation: 44370

You can use rescue keyword like this:

def ajax_action1
  item = Model1.where(id: params[:id]).first
  if item
    #....
  else
    render json: { errors: ['Not found'] }, status: 404
  end
rescue
  render json: { errors: ['Unexpected exception, try again later.'] }, status: 503
end

Method def can serve as a begin statement:

def ajax_action1
  ...
rescue
  ...
end

Upvotes: 1

Related Questions