Skip to content

Instantly share code, notes, and snippets.

@diloabininyeri
Last active February 28, 2023 09:24
Show Gist options
  • Save diloabininyeri/5c8c19f2dcb43b70e3c350dce6df86e0 to your computer and use it in GitHub Desktop.
Save diloabininyeri/5c8c19f2dcb43b70e3c350dce6df86e0 to your computer and use it in GitHub Desktop.
the advance handler exception class in php
<?php
class ExceptionHandler
{
private static array $exceptionHandlers = [];
public function __construct()
{
set_exception_handler(/**
* @throws ReflectionException
* @throws Throwable
*/ function (Throwable $e) {
$this->handleByInstanceParameter($e);
});
}
/**
* @throws ReflectionException
* @throws Throwable
*/
private function handleByInstanceParameter(Throwable $e): void
{
$isFound = false;
foreach (static::$exceptionHandlers as $exceptionHandler) {
$parameterClass = $this->getParameterClass($exceptionHandler);
if ($e instanceof $parameterClass) {
$exceptionHandler($e);
$isFound = true;
}
}
if ($isFound === false) {
throw $e;
}
}
/**
* @throws ReflectionException
*/
private function getParameterClass(Closure $exceptionHandler): string
{
$reflectionClosure = new ReflectionFunction($exceptionHandler);
$parameters = $reflectionClosure->getParameters();
return $parameters[0]->getType()?->getName();
}
public function add(Closure $closure): self
{
static::$exceptionHandlers[] = $closure;
return $this;
}
}
class RedirectException extends Exception
{
public function getRedirect(): string
{
return '/foo';
}
}
class CustomException extends Exception
{
}
$exceptionHandler = new ExceptionHandler();
$exceptionHandler
->add(function (RedirectException $redirectException) {
header('Location: ' . $redirectException->getRedirect());
exit(0);
});
$exceptionHandler
->add(static function (InvalidArgumentException $exceptionHandler) {
echo $exceptionHandler->getMessage();
});
$exceptionHandler->add(function (CustomException $e) {
var_dump($e->getMessage());
});
throw new CustomException('test');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment