title: Flask app: Heroku Postgres cannot load remembered user from db
body: <p>I have a simple Flask app on Heroku with '/login' route that is very standard (pretty much copied from famous Flask Mega Tutorial) and login form with ‘remember me’ functionality.</p>
  
  <p>Occasionally, I get the following server error when loading the app (error log is large, but the end is):</p>
  
  <pre><code>2020-05-25T18:01:05.614460+00:00 app[web.1]: sqlalchemy.exc.OperationalError: (psycopg2.errors.AdminShutdown) terminating connection due to administrator command
  2020-05-25T18:01:05.614460+00:00 app[web.1]: SSL connection has been closed unexpectedly
  2020-05-25T18:01:05.614460+00:00 app[web.1]: 
  2020-05-25T18:01:05.614462+00:00 app[web.1]: [SQL: SELECT "user".id AS user_id, "user".username AS user_username, "user".email AS user_email, "user".password_hash AS user_password_hash
  2020-05-25T18:01:05.614462+00:00 app[web.1]: FROM "user"
  2020-05-25T18:01:05.614463+00:00 app[web.1]: WHERE "user".id = %(param_1)s]
  2020-05-25T18:01:05.614463+00:00 app[web.1]: [parameters: {'param_1': 1}]
  2020-05-25T18:01:05.614621+00:00 app[web.1]: (Background on this error at: http://sqlalche.me/e/e3q8)
  </code></pre>
  
  <p>I believe the problem is that I have a logged in user that is 'remembered'. When loading the app next time, the app logs in 'remembered' user but sometimes drops the connection with the database (hence OperationaError above). The error is solved by simply loading the page once or twice again.</p>
  
  <p>The link <a href="http://sqlalche.me/e/e3q8" rel="nofollow noreferrer">http://sqlalche.me/e/e3q8</a> has the explanation that this is something outside of the control of the programmer. I do not have the skills to prevent this type of error, but I could at least detect it and reroute the user for better user experience.</p>
  
  <p><strong>Where in the typical Flask code could I check for this problem and instead of the user seeing ugly standard 'internal server error', reroute the user to my custom error page?</strong></p>
  
  <p>Normal entry point for a user is '/index' that does not require login but has this check to see if the user is logged in:</p>
  
  <pre><code>{% if current_user.is_authenticated %} 
  </code></pre>
  
  <p>Here is the beginning of my ‘/login’ route code:</p>
  
  <pre><code>@app.route('/login', methods=['GET', 'POST'])
  def login():
      if current_user.is_authenticated:
          return redirect(url_for('index'))
  </code></pre>