kurenn / market_place_api

The API on Rails tutorial application
142 stars 68 forks source link

500 error when user not exist #85

Open DevArenaCN opened 7 years ago

DevArenaCN commented 7 years ago

I'm working on the log in with sessions_controller, so my create function looks like this:

def create
    user_password = params[:session][:password]
    user_email = params[:session][:email]
    user = user_email.present? && User.find_by(email: user_email)
    if user and user.valid_password? user_password
      sign_in user, store: false
      user.generate_authentication_token!
      user.save
      render json: user, status: 200, location: [:api, user]
    else
      render json: { errors: "Invalid email or password" }, status: 422
    end
  end

So when the user does not exist, I got a 500 error instead of a 422. Any ideas? I tried rescue ActiveRecord::RecordNotFound but it's not working for me.

kurenn commented 7 years ago

On which part of the code is this failing?, I would say on the if, but what is the user variable value at that point?

DevArenaCN commented 7 years ago

So when the email does not exist in the ActiveRecord, it will throw out a 500 internal server error instead of a 422 Invalid email or password error.

kurenn commented 7 years ago

I think the user variable is nil, somehow, can you confirm this?

DevArenaCN commented 7 years ago

I can verify the login if the user exist in the database, which I don't think it's nil, right?

kurenn commented 7 years ago

I think you are getting the 500 because of this user.valid_password? user_password I'm not sure but it can be that the user is nil, so is trying to execute valid_password? over nil...it should not happen though...