From 39757b9f20f8cae185eb4f223d370b4553bd878a Mon Sep 17 00:00:00 2001 From: ArshiaMohammadei Date: Sat, 24 May 2025 12:53:19 +0330 Subject: [PATCH] Create Handler.php --- app/Exceptions/Handler.php | 62 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 app/Exceptions/Handler.php diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php new file mode 100644 index 0000000..2b1a289 --- /dev/null +++ b/app/Exceptions/Handler.php @@ -0,0 +1,62 @@ +expectsJson() || $request->is('api/*')) { + return $this->handleApiException($request, $e); + } + + return parent::render($request, $e); + } + + protected function handleApiException($request, Throwable $exception): JsonResponse + { + $statusCode = $this->getStatusCode($exception); + $response = [ + 'success' => false, + 'message' => $this->getErrorMessage($exception), + 'code' => $statusCode, + ]; + + if (config('app.debug')) { + $response['debug'] = [ + 'exception' => get_class($exception), + 'file' => $exception->getFile(), + 'line' => $exception->getLine(), + 'trace' => $exception->getTrace() + ]; + } + + return response()->json($response, $statusCode); + } + + protected function getStatusCode(Throwable $exception): int + { + return method_exists($exception, 'getStatusCode') + ? $exception->getStatusCode() + : Response::HTTP_INTERNAL_SERVER_ERROR; + } + + protected function getErrorMessage(Throwable $exception): string + { + return match (true) { + $exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException => __('errors.model_not_found'), + $exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException => __('errors.not_found'), + $exception instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException => __('errors.method_not_allowed'), + $exception instanceof \Illuminate\Http\Exceptions\ThrottleRequestsException => __('errors.too_many_requests'), + default => $exception->getMessage() ?: __('errors.server_error'), + }; + } +}