anonn023432
anonn023432

Reputation: 3120

Rails rescue standard error doesn't get sent

I have a controller method as follows

def create
  @game = Game.create_new_game(game_params)
  render 'show', status: 200
rescue StandardError => e
  render json: {
    status: 500,
    error: e.to_s
   }
end

I added a binding.pry and I can clearly see the following error in my console:

#<ActiveRecord::RecordInvalid: Validation failed: Name can't be blank, Duration can't be blank>

But it still sends the status:200 to the client side. Is there a different way the errors are supposed to be handled?

EDIT:

create_new_game method in Game

def self.create_new_game(prms)
  @player = Player.find(prms[:player].to_i)
  @game = @player.games.create!(
  name: prms[:name],
  duration: prms[:duration]
  )
  @game.save!
end

Upvotes: 0

Views: 1949

Answers (1)

max
max

Reputation: 102134

ActiveRecord does not normally raise an exception when a record is invalid. Its only when you use the "bang" methods like .create! that an exception is raised. Its also impossible for us to know what is going on inside Game.create_new_game. These are used for example in seed files wherethe developer should be aware that the validation failed or in nested transactions where it should trigger a rollback.

But what you're doing is not a good practice since exceptions should be used for exceptional events - not normal control flow.

Instead you should check the return value of saving/updating the record and determine the response.

def create
  @game = Game.create(game_params)
  if @game.save
    status: :created, location: @game
    # or
    render json: @game
  else
    render json: {
      status: 500,
      error: @game.errors.full_messages
    }
  end
end

Upvotes: 3

Related Questions