From 6a280e9ab5587ec49fd57d66029617d5d396852c Mon Sep 17 00:00:00 2001 From: Maarten Date: Mon, 25 Nov 2024 20:23:54 +0100 Subject: [PATCH] Get exception handler based on debug --- src/Exceptions/Exceptions.php | 36 ++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/src/Exceptions/Exceptions.php b/src/Exceptions/Exceptions.php index fb2602b..ceb5f31 100644 --- a/src/Exceptions/Exceptions.php +++ b/src/Exceptions/Exceptions.php @@ -2,7 +2,12 @@ namespace Core\Exceptions; +use Core\Env\Env; +use Core\Http\Request; use Throwable; +use Whoops\Handler\Handler; +use Whoops\Handler\JsonResponseHandler; +use Whoops\Handler\PlainTextHandler; use Whoops\Handler\PrettyPageHandler; use Whoops\Run as Whoops; @@ -18,13 +23,14 @@ class Exceptions /** * Get exceptions handler instance * + * @param \Core\Http\Request|null $request * @return \Whoops\Run */ - public static function handler(): Whoops + public static function instance(Request|null $request = null): Whoops { if (!isset(self::$instance)) { $instance = new Whoops(); - $instance->pushHandler(new PrettyPageHandler()); + $instance->pushHandler(self::handler($request)); self::$instance = $instance; } @@ -32,14 +38,34 @@ class Exceptions return self::$instance; } + /** + * Get correct handler + * + * @param \Core\Http\Request|null $request + * @return \Whoops\Handler\Handler + */ + private static function handler(Request|null $request): Handler + { + if (Env::get('debug')) { + if ($request?->is('post')) { + return new JsonResponseHandler(); + } + + return new PrettyPageHandler(); + } + + return new PlainTextHandler(); + } + /** * Catch all exceptions * + * @param \Core\Http\Request $request * @return void */ - public static function catch(): void + public static function catch(Request $request): void { - self::handler()->register(); + self::instance($request)->register(); } /** @@ -50,6 +76,6 @@ class Exceptions */ public static function catchOne(Throwable $exception): void { - self::handler()->handleException($exception); + self::instance()->handleException($exception); } } \ No newline at end of file