From b2de69a9ba76112ed28ccfe560728454ff11a2dc Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Sat, 23 Aug 2025 18:45:56 +0200 Subject: [PATCH] feat(auth): enhance API error handling for authorization exceptions --- app/Exceptions/Handler.php | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 8c89bb07f..275de57c0 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -53,6 +53,35 @@ class Handler extends ExceptionHandler return redirect()->guest($exception->redirectTo($request) ?? route('login')); } + /** + * Render an exception into an HTTP response. + */ + public function render($request, Throwable $e) + { + // Handle authorization exceptions for API routes + if ($e instanceof \Illuminate\Auth\Access\AuthorizationException) { + if ($request->is('api/*') || $request->expectsJson()) { + // Get the custom message from the policy if available + $message = $e->getMessage(); + + // Clean up the message for API responses (remove HTML tags if present) + $message = strip_tags(str_replace('
', ' ', $message)); + + // If no custom message, use a default one + if (empty($message) || $message === 'This action is unauthorized.') { + $message = 'You are not authorized to perform this action.'; + } + + return response()->json([ + 'message' => $message, + 'error' => 'Unauthorized', + ], 403); + } + } + + return parent::render($request, $e); + } + /** * Register the exception handling callbacks for the application. */