title: How do I handle errors in passport.deserializeUser()?
body: <p>I've got Express and Passport configured like so:</p>
  
  <pre><code>var express = require("express");
  var site = express();
  var flash = require("connect-flash");
  var passport = require("passport");
  
  site.use(require("cookie-parser")());
  site.use(require("body-parser").urlencoded({extended:false}));
  site.use(require("express-session")(...));
  site.use(flash());
  site.use(passport.initialize());
  site.use(passport.session());
  </code></pre>
  
  <p>I've got a pretty stock implementation of <code>deserializeUser</code> (I'm using <code>local</code> authentication backed by MySQL via Bookshelf):</p>
  
  <pre><code>var db = require("./database.js"); // exports models e.g. db.User
  
  passport.deserializeUser(function(id, done) {
      db.User.findById(id).then(function (user) {
          done(null, user);
      }).catch(function (err) {
          done(err, null);
      });
  });
  </code></pre>
  
  <p>I'm running in to the following specific problem: When a logged-in user is deleted from the database (happens when e.g. a site administrator deletes the user), the deserialization fails, as expected, with a <code>CustomError("EmptyResponse")</code> from Bookshelf. However, I don't know how to handle it; <code>done(err, null)</code> ultimately just causes the error message and stack trace to get sent back as HTML to the client.</p>
  
  <p>The question is: <strong>How can I provide custom, graceful error handling from <code>deserializeUser</code> on a failure?</strong></p>
  
  <p>Now, if it simplifies things, I could add <code>{require:false}</code> to the <code>db.User.findById</code> call to give me a <code>null</code> user instead of an error, but I still don't know how to handle it (and also I still do need to handle error objects e.g. if the database server is down and there's a connection error).</p>
  
  <p>The action I want to take on failure is to redirect the user back to the login page, potentially with a descriptive flash message, but I don't have any access to the request/response in <code>deserializeUser</code> and I'm not sure how to communicate back.</p>