Skip to content

Commit

Permalink
Merge pull request #748 from KnpLabs/fix-exception
Browse files Browse the repository at this point in the history
listen to other exceptions
  • Loading branch information
garak authored Dec 26, 2022
2 parents 7908650 + f940e2b commit 92d676e
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/EventListener/ExceptionListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
namespace Knp\Bundle\PaginatorBundle\EventListener;

use OutOfRangeException;
use Knp\Component\Pager\Exception\InvalidValueException;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use UnexpectedValueException;
use function preg_match;

/**
* Intercept OutOfRangeException and throw http-related exceptions instead.
* Intercept OutOfRangeException/UnexpectedValueException and throw http-related exceptions instead.
*/
final class ExceptionListener
{
Expand All @@ -16,6 +19,30 @@ public function onKernelException(ExceptionEvent $event): void
$exception = $event->getThrowable();
if ($exception instanceof OutOfRangeException) {
$event->setThrowable(new NotFoundHttpException('Not Found.', $exception));
} elseif ($exception instanceof InvalidValueException) {
$event->setThrowable(new NotFoundHttpException('Not Found.', $exception));
} elseif ($exception instanceof UnexpectedValueException && self::isInternalException($exception)) {
$event->setThrowable(new NotFoundHttpException('Not Found', $exception));
}
}

private static function isInternalException(UnexpectedValueException $exception): bool
{
$messages = [
'/^Cannot filter by\: \[.+\] this field is not in allow list$/',
'/^Cannot sort by\: \[.+\] this field is not in allow list\.$/',
'/^Cannot sort with array parameter$/',
'/^ODM query must be a FIND type query$/',
'/^There is no component aliased by \[.+\] in the given Query$/',
'/^There is no component field \[.+\] in the given Query$/',
'/^There is no such field \[.+\] in the given Query component, aliased by \[.+\]$/',
];
foreach ($messages as $regex) {
if (preg_match($regex, $exception->getMessage()) > 0) {
return true;
}
}

return false;
}
}

0 comments on commit 92d676e

Please sign in to comment.