|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Foundation\Api\Exceptions\V1\BaseExceptionHandler; |
| 6 | + |
| 7 | +use Foundation\Api\Services\V1\Api\Api; |
| 8 | +use Illuminate\Auth\AuthenticationException; |
| 9 | +use Illuminate\Database\Eloquent\ModelNotFoundException; |
| 10 | +use Illuminate\Database\QueryException; |
| 11 | +use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; |
| 12 | +use Illuminate\Http\Exceptions\ThrottleRequestsException; |
| 13 | +use Illuminate\Http\JsonResponse; |
| 14 | +use Illuminate\Http\RedirectResponse; |
| 15 | +use Illuminate\Http\Request; |
| 16 | +use Illuminate\Validation\ValidationException; |
| 17 | +use Symfony\Component\HttpFoundation\Response; |
| 18 | +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; |
| 19 | +use Throwable; |
| 20 | + |
| 21 | +/** |
| 22 | + * BaseExceptionHandler |
| 23 | + * |
| 24 | + * Centralizes exception reporting and rendering for API + web. |
| 25 | + * - Sends exceptions to Sentry if bound. |
| 26 | + * - Returns consistent JSON for API requests using the Api response builder. |
| 27 | + * - Avoids leaking sensitive error messages in production. |
| 28 | + */ |
| 29 | +class BaseExceptionHandler extends ExceptionHandler |
| 30 | +{ |
| 31 | + /** |
| 32 | + * Register the exception handler. |
| 33 | + * |
| 34 | + * - Keeps Laravel defaults via parent::register(). |
| 35 | + * - Reports to Sentry if container has a 'sentry' binding. |
| 36 | + * |
| 37 | + * @return void |
| 38 | + */ |
| 39 | + public function register(): void |
| 40 | + { |
| 41 | + parent::register(); |
| 42 | + |
| 43 | + $this->reportable(function (Throwable $e): void |
| 44 | + { |
| 45 | + if (app()->bound('sentry')) |
| 46 | + { |
| 47 | + app('sentry')->captureException($e); |
| 48 | + } |
| 49 | + }); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Render an exception into an HTTP response. |
| 54 | + * |
| 55 | + * For API requests (`expectsJson()` or `api/*`), return a normalized JSON payload. |
| 56 | + * Otherwise, fall back to the default web rendering. |
| 57 | + * |
| 58 | + * @param Request $request |
| 59 | + * @param Throwable $e |
| 60 | + * @return \Illuminate\Http\Response|JsonResponse|RedirectResponse|Response |
| 61 | + * @throws Throwable |
| 62 | + */ |
| 63 | + public function render($request, Throwable $e): \Illuminate\Http\Response|JsonResponse|RedirectResponse|Response |
| 64 | + { |
| 65 | + if ($this->isApiRequest($request)) |
| 66 | + { |
| 67 | + return $this->handleApiExceptions($request, $e); |
| 68 | + } |
| 69 | + |
| 70 | + return parent::render($request, $e); |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * Determine if the incoming request targets the API. |
| 75 | + * |
| 76 | + * @param Request $request |
| 77 | + * @return bool |
| 78 | + */ |
| 79 | + protected function isApiRequest(Request $request): bool |
| 80 | + { |
| 81 | + return $request->expectsJson() || $request->is('api/*'); |
| 82 | + } |
| 83 | + |
| 84 | + /** |
| 85 | + * Handle exceptions for API requests in a safe, consistent way. |
| 86 | + * |
| 87 | + * @param Request $request |
| 88 | + * @param Throwable $exception |
| 89 | + * @return \Illuminate\Http\Response|JsonResponse|RedirectResponse|Response |
| 90 | + * @noinspection PhpUnusedParameterInspection |
| 91 | + */ |
| 92 | + private function handleApiExceptions(Request $request, Throwable $exception): \Illuminate\Http\Response|JsonResponse|RedirectResponse|Response |
| 93 | + { |
| 94 | + $debug = (bool) config('app.debug'); |
| 95 | + |
| 96 | + return match (true) |
| 97 | + { |
| 98 | + $exception instanceof AuthenticationException => Api::response()->unauthorized()->send(), |
| 99 | + |
| 100 | + $exception instanceof ThrottleRequestsException => $this->throttledResponse($exception), |
| 101 | + |
| 102 | + $exception instanceof ModelNotFoundException, |
| 103 | + $exception instanceof NotFoundHttpException => Api::response()->notFound()->send(), |
| 104 | + |
| 105 | + $exception instanceof ValidationException => Api::response() |
| 106 | + ->message($exception->getMessage() ?: null) |
| 107 | + ->errors($exception->errors()) |
| 108 | + ->send(), |
| 109 | + |
| 110 | + // Database/Query errors: generic message in production |
| 111 | + $exception instanceof QueryException => Api::response() |
| 112 | + ->internalError($debug ? $exception->getMessage() : null) |
| 113 | + ->send(), |
| 114 | + |
| 115 | + // Fallback: generic failed response (400) in prod, include message in debug |
| 116 | + default => Api::response() |
| 117 | + ->failed() |
| 118 | + ->message($debug ? $exception->getMessage() : null) |
| 119 | + ->send(), |
| 120 | + }; |
| 121 | + } |
| 122 | + |
| 123 | + /** |
| 124 | + * Build a throttled (429) response and attach Retry-After metadata when available. |
| 125 | + * |
| 126 | + * @param ThrottleRequestsException $exception |
| 127 | + * @return JsonResponse |
| 128 | + */ |
| 129 | + protected function throttledResponse(ThrottleRequestsException $exception): JsonResponse |
| 130 | + { |
| 131 | + $retryAfter = null; |
| 132 | + |
| 133 | + // ThrottleRequestsException usually carries headers with Retry-After |
| 134 | + $headers = method_exists($exception, 'getHeaders') ? $exception->getHeaders() : []; |
| 135 | + if (isset($headers['Retry-After'])) |
| 136 | + { |
| 137 | + $retryAfter = (int) $headers['Retry-After']; |
| 138 | + } |
| 139 | + |
| 140 | + $api = Api::response()->throttled(); |
| 141 | + |
| 142 | + if (null !== $retryAfter) |
| 143 | + { |
| 144 | + $api->addMeta('retry_after', $retryAfter); |
| 145 | + } |
| 146 | + |
| 147 | + return $api->send(); |
| 148 | + } |
| 149 | +} |
0 commit comments