From bc736be13c87a858df80911b287d0eca1cf8b670 Mon Sep 17 00:00:00 2001 From: Angelin Date: Sat, 29 Feb 2020 11:26:39 +0200 Subject: [PATCH] Allows Errors in $router->exceptionRoute method I have extended the $router->exceptionRoute() method to be able to catch Throwable Errors that are not being caught by $router->errorRoute() method. Ex: $router->exceptionRoute(Error::class, function (\Error $e) use ($logger) { $logger->error($e); ... }); --- library/Respect/Rest/Request.php | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/library/Respect/Rest/Request.php b/library/Respect/Rest/Request.php index e9cf0fa..899aad7 100644 --- a/library/Respect/Rest/Request.php +++ b/library/Respect/Rest/Request.php @@ -213,6 +213,30 @@ protected function catchExceptions($e) } } + /** + * Does a catch-like operation on an error based on previously + * declared instances from Router::exceptionRoute + * + * @param Error $e Any exception + * + * @return mixed A route forwarding or a silent null + */ + protected function catchErrors($e) + { + foreach ($this->route->sideRoutes as $sideRoute) { + $errorClass = get_class($e); + if ( + $errorClass === $sideRoute->class + || $sideRoute->class === 'Error' + || $sideRoute->class === '\Error' + ) { + $sideRoute->exception = $e; + + return $this->forward($sideRoute); + } + } + } + /** * Generates and returns the response from the current route * @@ -256,6 +280,14 @@ public function response() //Returns whatever the exception routes returned return (string) $exceptionResponse; + } catch (\Error $e) { + //Tries to catch it using catchErrors() + if (!$errorResponse = $this->catchErrors($e)) { + throw $e; + } + + //Returns whatever the exception routes returned + return (string) $errorResponse; } }