Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

feat(auth): enhance API error handling for authorization exceptions

Andras Bacsaib2de69a9ba76
diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php
index 8c89bb07f9..275de57c00 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('<br/>', ' ', $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.
*/