title: AWS API Gateway with Lambda Authorizer returns 500 instead of 401
body: <p>I'm building an AWS Lambda Request Authorizer for API Gateway. The stack uses Serverless Framework and the Lambda is in Java.</p>
  <ul>
  <li>When the provided <code>Authorization</code> header (API key) is valid, everything works as expected.</li>
  <li>When the <code>Authorization</code> header is missing, a 401 response is returned, as expected. In this scenario, API GW doesn't even call the authorizer.</li>
  <li>When an invalid <code>Authorization</code> header is provided, the lambda throws a <code>RuntimeException(&quot;Unauthorized&quot;)</code>. I would expect API GW to return a 401 error, but instead a <code>500 Internal Server</code> error is received. Not good.</li>
  </ul>
  <p>Here's the lambda request handler code:</p>
  <pre class="lang-java prettyprint-override"><code>@Override
  public AuthPolicy handleRequest(AuthorizerEvent authorizerEvent, Context context) {
      try {
          return getPolicy(authorizerEvent);
      } catch (Exception exception) {
          throw new RuntimeException(&quot;Unauthorized&quot;);
      }
  }
  </code></pre>
  <p>CloudWatch confirms the RuntimeException is thrown:</p>
  <pre><code>&lt;last message logged by authorizer&gt;
  
  Unauthorized: java.lang.RuntimeException
  java.lang.RuntimeException: Unauthorized
      at com.example.serverless.AuthorizerHandler.handleRequest(AuthorizerHandler.java:30)
      at com.example.serverless.AuthorizerHandler.handleRequest(AuthorizerHandler.java:20)
  </code></pre>
  <p>Here's the log when testing the authorizer in the AWS Console, which indicates the error condition was not handled correctly or at all:</p>
  <pre><code>&gt; Authorizer result body before parsing: {}
  &gt; Execution failed due to configuration error: Could not parse policy due to null response or empty JSON.
  &gt; AuthorizerConfigurationException
  </code></pre>
  <p>What am I doing wrong or not doing right?</p>