title: PHP: Slim Framework Exception Handling
body: <p>I just finished creating an API application with slim framework, initially, in my code I use a dependency container to handle all exceptions thrown, the code is below.</p>
  
  <pre><code>//Add container to handle all exceptions/errors, fail safe and return json
  $container['errorHandler'] = function ($container) {
      return function ($request, $response, $exception) use ($container) {
          //Format of exception to return
          $data = [
              'message' =&gt; $exception-&gt;getMessage()
          ];
          return $container-&gt;get('response')-&gt;withStatus(500)
              -&gt;withHeader('Content-Type', 'application/json')
              -&gt;write(json_encode($data));
      };
  };
  </code></pre>
  
  <p>But instead of throwing a 500 <code>Server Error</code> all the time I would like to add other HTTPS reponse code. I wonder if I could get help on how to go about that.</p>
  
  <pre><code>public static function decodeToken($token)
  {
      $token = trim($token);
      //Check to ensure token is not empty or invalid
      if ($token === '' || $token === null || empty($token)) {
          throw new JWTException('Invalid Token');
      }
      //Remove Bearer if present
      $token = trim(str_replace('Bearer ', '', $token));
  
      //Decode token
      $token = JWT::decode($token, getenv('SECRET_KEY'), array('HS256'));
  
      //Ensure JIT is present
      if ($token-&gt;jit == null || $token-&gt;jit == "") {
          throw new JWTException('Invalid Token');
      }
  
      //Ensure User Id is present
      if ($token-&gt;data-&gt;uid == null || $token-&gt;data-&gt;uid == "") {
          throw new JWTException("Invalid Token");
      }
      return $token;
  }
  </code></pre>
  
  <p>The problem is even more from functions like the above one, since slim framework decides to handle all exceptions implicitly, I have no access to use <code>try catch</code> to catch any errors</p>