0

I am debugging a problem about simple_token_authentication, I modified some code in https://github.com/gonzalo-bulnes/simple_token_authentication/blob/master/lib/simple_token_authentication/sign_in_handler.rb#L7 to:

def sign_in(controller, record, *args)
  begin
    puts "=== TRACE 1"
    integrate_with_devise_trackable!(controller)
    puts "=== TRACE 2"
    controller.send(:sign_in, record, *args)
    puts "=== TRACE 3"
  rescue Exception => e
    puts "=== TRACE 4"
  ensure
    puts "=== TRACE 5"
  end
end

Outputs:

Started GET "/projects" for ::1 at 2016-04-18 18:35:22 +0800
  ActiveRecord::SchemaMigration Load (0.1ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by ProjectsController#index as JSON
  Parameters: {"project"=>{}}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["email", "testaccount@gmail.com"]]
=== TRACE 1
=== TRACE 2
   (0.1ms)  begin transaction
   (0.0ms)  commit transaction
=== TRACE 5
Completed 401 Unauthorized in 40ms (ActiveRecord: 0.9ms)

The question isn't about simple_token_authentication, the question is why TRACE 3 and TRACE 4 both didn't output? Is there a possibly reason could cause th?

My environment:

  • ruby-2.2.3 [ x86_64 ] installed by rvm
  • Mac OSX 10.11.4
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Jacky Lee
  • 1,232
  • 1
  • 9
  • 11

1 Answers1

5

Devise and warden use throw/catch to communicate that warden was unable to sign the user in. As long as there is a matching catch block higher up on the stack, throw doesn't raise an exception so the rescue clause isn't called. Ensure is called because it's always supposed to be called. You can test this with this small snippet:

def test
  puts "about to throw"
  throw :rock, :hard
rescue Exception => e
  puts "exception: #{e.message}"
ensure
  puts "ensure"
end

result = catch(:rock) { test }
puts result

the rescue clause won't ever execute, but if you just call test on its own then you'll get an UncaughtThrowException handled by the block.

In this case, devise provides a rack middleware that catches what warden throws.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174