I'm trying to catch an error from my JWT class but I can't do it inside the class, the only place I can get it is from my main caller.
I'm calling this class with the error from my "API" where I start with the routing:
$router = new Router();
$router->all('/users', function()
{
$controller = new Controllers\UserController();
$controller->start();
});
$router->run();
After that I have my controller that will call my "API" class:
class UserAPI extends BaseAPI
{
protected $user;
protected $apiBase = "user";
function __construct($request, $origin)
{
parent::__construct($request);
$this->user = new User();
}
protected function logout()
{
if( isset($this->request[$this->apiBase . 'Data']) )
{
return $this->usuario->login($this->request[$this->apiBase . 'Data']);
}
else
{
return Helpers::errorResponse("User data not informed", 200);
}
}
}
And finally I have the problem, the User class where I want to catch an error but it won't work:
class User extends SimpleModel
{
public function logout($userData)
{
try
{
//At this point I will get an error since the provided token is invalid on purpose
$jwt = JWT::decode($userData['token'], SECRET_KEY, ['HS512']);
}
//Wont hit here even for a miracle
catch (Exception $exception)
{
echo "Caught ExceptFoo\n";
echo "Message: {$exception->getMessage()}\n";
}
}
}
The only place I could catch this error was on the routing file, which is my index.php file.
For the JWT class I'm using Firebase JWT.
Relative class names (like Exception
in your example) are always rooted to the namespace you are within. If you don't define a namespace, \
is used. Consider:
<?php
namespace Foo;
use Vendor\Package\Bar;
try {
Bar::throwAnException();
} catch (Exception $ex) {
die((string)$ex);
}
Here we have two relative class paths: Bar
and Exception
. PHP resolves Bar
via the use
statement to the absolute class path \Vendor\Package\Bar
. PHP doesn't have a use
statement corresponding to Exception
, so PHP assumes you mean \Foo\Exception
.
Clearly this isn't your intent. Unfortunately, PHP is silent when this situation occurs. It's bitten me a few times.