From 3f99b00cf792bae5ff70fa1ffe795ff3cf62f422 Mon Sep 17 00:00:00 2001 From: DaneEveritt Date: Sun, 22 May 2022 18:21:38 -0400 Subject: [PATCH] Fix display exception handling --- app/Exceptions/DisplayException.php | 17 +++++++++++++++-- app/Exceptions/Handler.php | 9 +++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/app/Exceptions/DisplayException.php b/app/Exceptions/DisplayException.php index 636b9dfc9..c7b3b2edb 100644 --- a/app/Exceptions/DisplayException.php +++ b/app/Exceptions/DisplayException.php @@ -8,8 +8,9 @@ use Psr\Log\LoggerInterface; use Illuminate\Http\Response; use Illuminate\Container\Container; use Prologue\Alerts\AlertsMessageBag; +use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; -class DisplayException extends PterodactylException +class DisplayException extends PterodactylException implements HttpExceptionInterface { public const LEVEL_DEBUG = 'debug'; public const LEVEL_INFO = 'info'; @@ -51,6 +52,14 @@ class DisplayException extends PterodactylException return Response::HTTP_BAD_REQUEST; } + /** + * @return array + */ + public function getHeaders() + { + return []; + } + /** * Render the exception to the user by adding a flashed message to the session * and then redirecting them back to the page that they came from. If the @@ -58,10 +67,14 @@ class DisplayException extends PterodactylException * * @param \Illuminate\Http\Request $request * - * @return \Illuminate\Http\RedirectResponse + * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse */ public function render($request) { + if ($request->expectsJson()) { + return response()->json(Handler::toArray($this), $this->getStatusCode(), $this->getHeaders()); + } + app(AlertsMessageBag::class)->danger($this->getMessage())->flash(); return redirect()->back()->withInput(); diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 2155f6c3d..60ee4d542 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -284,4 +284,13 @@ class Handler extends ExceptionHandler return $previous; } + + /** + * Helper method to allow reaching into the handler to convert an exception + * into the expected array response type. + */ + public static function toArray(Throwable $e): array + { + return (new self(app()))->convertExceptionToArray($e); + } }