mardi 16 octobre 2018

How to handle user equal nil when it is not detected by ActiveRecord::RecordNotFound

I am learning programming only, Ruby on Rails in particular. The problem I face currently is that I doubt in which way to handle my issue is better regarding clean code and avoiding my code smells or probably something else.

So basically, I have users_controller where I check if my jwt is valid: I decode it, withdraw user_id and look for the user in DB by her id.

 def login
    user = decoded_user(permitted_params[:jwt])
    render json: user
  rescue ActiveRecord::RecordNotFound, JWT::DecodeError
    render status: 401, json: { error: 'invalid token' }.to_json
  end

As you can see, in case of invalid jwt or user is not found, it must render 401 error, but somehow when user is nil, rescue ActiveRecord::RecordNotFound does not detect it and render 200 status when I want it 401. When jwt is valid or empty, it all works fine.

I was thinking to wrap it into if else block in case of nil though to me it does not seem really skilled. Could you help me to refactor, please? Thanks!

Aucun commentaire:

Enregistrer un commentaire