title: graphql + apollo-server-express, how to handle auth error in express authMiddleware?
body: <p>I can't figure out how to handle auth error in my authMiddleware function.</p>
  
  <p>Here is my <code>authMiddleware</code> function with traditional express way error handling.</p>
  
  <pre><code>const jwt = require('jsonwebtoken');
  const { appConfig } = require('../config');
  
  function authMiddleware(req, res, next) {
    let token;
    const parts = req.headers.authorization.split(' ');
  
    if (parts.length === 2) {
      const schema = parts[0];
      const credentials = parts[1];
  
      if (/^Bearer$/i.test(schema)) {
        token = credentials;
      } else {
        // throw new Error();
        next(new Error('credentials_bad_scheme: Format is Authorization: Bearer [token]'));
      }
    }
  
    try {
      const { user } = jwt.verify(token, appConfig.JWT_SCERET);
      req.user = user;
    } catch (error) {
      // console.log(error);
      next(error);
    }
    next();
  }
  
  exports.authMiddleware = authMiddleware;
  </code></pre>
  
  <p>But with <code>apollo-server-express</code> and <code>graphql</code> system. The <code>error</code> passed into <code>next</code> function does not work fine. Which means it seems the <code>express</code> error handling way is not working any more when use <code>graphql</code> tool stack.</p>
  
  <p>The <code>error</code> in <code>authMiddleware</code> will not pass below express error handling middleware</p>
  
  <pre><code>app.use((err, req, res) =&gt; {
    console.log('error handler: ', err);
  });
  </code></pre>
  
  <p>If I use <code>return res.status(401).json({code: 1001, msg: 'Authorization failed'})</code> or <code>throw new Error('xxx')</code> in <code>catch</code> when auth failed. The request will stop here forever which means will never go down to <code>graphqlExpressHandler</code>. In order to let request go down to <code>graphqlExpressHandler</code>, only thing I can do for the errors is to use <code>console.log</code> to print them. </p>
  
  <p>And there is no way to use <code>express-jwt</code> <code>unless</code> method or <code>credentialsRequired</code> property. <strong>Because when use graphql, there is only one route named '/graphql'. So, you can't unless /graphql route</strong></p>
  
  <p>One way to solve this is: make restful api for <code>auth</code> and handle it in traditonal way. Make <code>graphql</code> api for data query.</p>