Handling “Session key invalid or no longer valid” errors from Facebook

I’m not sure if it’s supposed to work this way, but Facebook’s PHP client library method get_loggedin_user() doesn’t do the best job of keeping track of valid sessions. I seem to recall that even their demo FB Connect application experienced this error… It’s easy to reproduce on many FB Connect sites; log into a FB Connect site, then go to Facebook, logout of Facebook, and return to your FB Connect site. Reload the page and you’ll likely see a Session key invalid or no longer valid error followed by a trace.
So simple solution would be to catch the error; problem is that I don’t think it’s terribly obvious how to properly release the session if an error is caught… Using CakePHP, I added the following to my beforeFilter method:

if($this->facebook->get_loggedin_user()):
try {
$this->user = $this->facebook->api_client->fql_query('SELECT uid, pic_square, first_name FROM user WHERE uid = ' . $this->facebook->get_loggedin_user());
} catch (Exception $ex) {
$this->facebook->clear_cookie_state();
}
endif;

So the only way to reliably test whether or not you have a valid session (since get_loggedin_user() can’t be trusted) is to run a method that requires one, and see if it throws an error. Sure, it adds overhead which is why I’d recommend a light FQL query which will return data I need anyway, but it’s much better than throwing fatal errors.
If an error is found, clear_cookie_state() seems to effectively destroy the session, and get_loggedin_user() will properly return false in all subsequent code.