I have an abstract class that wraps PHP exception:
abstract class MyException extends Exception
{
public function __construct($message, $code = 0, Exception $previous = null)
{
parent::__construct($message, (int) $code, $previous);
}
}
Then I have other classes like:
class UserException extends MyException
{
public function __toString()
{
return parent::getMessage();
}
}
When try throw an error doing throw new UserException('User does not exist');
It doesn’t only show the message I defined. It shows:
Fatal error: Uncaught User does not exist thrown in
\path\ClassTest.php on line 69
How do I get rid of the “Fatal error: Uncaught…” portion?
Thanks a lot.
EDIT:
I’ve found the answer, using set_exception_handler() will override uncaught exceptions. And allow to provide a callback function
The “fatal error” part is generated because the exception is thrown outside a try-catch statement, and is finally caught by the php error handler. Uncaught exceptions are always fatal.
Try surrounding the code that generates the exception with a try-catch statement like:
Alternately you could make your own error handler –> Linky.
But the try-catch approach is the “correct” way to do it.