Slim Trying To Handle Exceptions in Try Catch

I am developing a REST API using JWT token authentication and it is my first time using Slim. I am using Slim 3 and Firebase/php-jwt for handing token encoding/decoding.

I have some middleware setup on some of my routes that runs a check function to determine if the user has provided a valid token. Within this check function, I attempt to decode a token using Firebase/JWT. Firebase/JWT will either return a token object or throw an exception if it is unable to decode, as such, I wrap the decode method in a try/catch so that I can return true or false to my check method.

The problem I am encountering is that even though I am handling the decode error with a try/catch, Slim is still somehow seeing the Exception and returning a 500 Internal Server Error as if I had not used a try/catch at all. How can I prevent Slim from handling exceptions that have already been handled with a try/catch?

Auth Model:

namespace App\Models;

use App\Models\Token;

class Auth
{
    /**
    * check: Verifies the user has a valid session token.
    *
    * @param    string      $token 
    * @return   boolean     Success - true; Fail - false 
    */
    public function checkIntranetHub($token)
    {
        // If token is set
        if (!empty($token) && !empty($token[0])) {
            // If token format is valid
            if ($tokenObj = Token::decode($token[0])){
                    return true;   
            }
        }

        return false;
    }
}

Token Model:

namespace App\Models;

use \Firebase\JWT\JWT;

class Token
{
    private static $secret = 'secret';

    public static function create($username)
    {
        $payload = array(
            'uname' => $username,
            'iat' => date('YmdHis')
        );

        return JWT::encode($payload, self::$secret);
    }

    public static function decode($token)
    {
        try{
            $tokenObj = JWT::decode($token, self::$secret);

            if (empty($tokenObj->uname)){
                return false;
            }

            return true;
        }
        catch (Exception $e){
            return false;
        }
    }
}

Hello Ginevive,

Try adding a slash before Exception in the catch argument to indicate the Exception class in the default namespace instead of \App\Models\Exception:

    catch(\Exception $e) {
1 Like