Skip to content

Instantly share code, notes, and snippets.

@ADmad
Created January 3, 2026 14:13
Show Gist options
  • Select an option

  • Save ADmad/6a571fd041353a45a8c824debe58664d to your computer and use it in GitHub Desktop.

Select an option

Save ADmad/6a571fd041353a45a8c824debe58664d to your computer and use it in GitHub Desktop.
diff --git a/src/Http/BaseApplication.php b/src/Http/BaseApplication.php
index d1e51db584..da3a9d5a0f 100644
--- a/src/Http/BaseApplication.php
+++ b/src/Http/BaseApplication.php
@@ -350,13 +350,18 @@ abstract class BaseApplication implements
$eventManager = $this->events($this->getEventManager());
$this->setEventManager($this->pluginEvents($eventManager));
- $this->controllerFactory ??= new ControllerFactory($container);
-
if (Router::getRequest() !== $request) {
assert($request instanceof ServerRequest);
Router::setRequest($request);
}
+ /** @var \Throwable|null $exception */
+ $exception = $request->getAttribute('exception');
+ if ($exception) {
+ throw $exception;
+ }
+
+ $this->controllerFactory ??= new ControllerFactory($container);
$controller = $this->controllerFactory->create($request);
return $this->controllerFactory->invoke($controller);
diff --git a/src/Routing/Middleware/RoutingMiddleware.php b/src/Routing/Middleware/RoutingMiddleware.php
index 68f6b276f0..d7a3d33ec1 100644
--- a/src/Routing/Middleware/RoutingMiddleware.php
+++ b/src/Routing/Middleware/RoutingMiddleware.php
@@ -22,6 +22,7 @@ use Cake\Http\Exception\RedirectException;
use Cake\Http\MiddlewareQueue;
use Cake\Http\Runner;
use Cake\Http\ServerRequest;
+use Cake\Routing\Exception\MissingRouteException;
use Cake\Routing\Router;
use Cake\Routing\RoutingApplicationInterface;
use Laminas\Diactoros\Response\RedirectResponse;
@@ -98,12 +99,21 @@ class RoutingMiddleware implements MiddlewareInterface
Router::setRequest($request);
}
- } catch (RedirectException $e) {
- return new RedirectResponse(
- $e->getMessage(),
- $e->getCode(),
- $e->getHeaders(),
- );
+ } catch (RedirectException | MissingRouteException $e) {
+ if ($e instanceof RedirectException) {
+ return new RedirectResponse(
+ $e->getMessage(),
+ $e->getCode(),
+ $e->getHeaders(),
+ );
+ }
+
+ $request = $request->withAttribute('params', ['controller' => 'Error', 'action' => 'error400', 'pass' => []]);
+ $request = $request->withAttribute('exception', $e);
+
+ Router::setRequest($request);
+
+ return $handler->handle($request);
}
$matching = Router::getRouteCollection()->getMiddleware($middleware);
if (!$matching) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment