From 702419b95bf5c5beae57dd1abb8fdfc39b0bec3a Mon Sep 17 00:00:00 2001 From: Alireza Kamali Date: Thu, 13 May 2021 11:57:48 +0430 Subject: [PATCH] HandlerException added --- CHANGELOG.md | 4 ++ src/HandlerException.php | 101 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 src/HandlerException.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c977df..e225226 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to `hooshid/laravel-utils` will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.3.5] - 2021-05-13 +### Added +- HandlerException class. + ## [0.3.1] - 2021-05-07 ### Added - php info page. diff --git a/src/HandlerException.php b/src/HandlerException.php new file mode 100644 index 0000000..9c4874f --- /dev/null +++ b/src/HandlerException.php @@ -0,0 +1,101 @@ +expectsJson() && method_exists($e, 'getStatusCode')) { + return response()->json([ + 'result' => [ + 'status' => 'error', + 'code' => $e->getStatusCode(), + 'description' => $e->getMessage(), + ], + ], $e->getStatusCode()); + } + + // catch only json requests + if ($request->expectsJson()) { + + // 400 Bad Request + if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) { + return response()->json([ + 'result' => [ + 'status' => 'error', + 'code' => 400, + 'description' => 'Bad Request', + ], + ], 400); + } + + // 401 Unauthorized + if ($e instanceof \Illuminate\Auth\AuthenticationException) { + return response()->json([ + 'result' => [ + 'status' => 'error', + 'code' => 401, + 'description' => 'Unauthorized', + ], + ], 401); + } + + // 404 Not Found + if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) { + return response()->json([ + 'result' => [ + 'status' => 'error', + 'code' => 404, + 'description' => 'Not Found', + ], + ], 404); + } + + // 422 Unprocessable Entity - Validation Form + if ($e instanceof \Illuminate\Validation\ValidationException) { + return response()->json([ + 'result' => [ + 'status' => 'error', + 'code' => 422, + 'description' => 'Unprocessable Entity', + ], + 'errors' => $e->errors(), + ], 422); + } + + // 422 Unprocessable Entity + if ($e instanceof \Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException) { + return response()->json([ + 'result' => [ + 'status' => 'error', + 'code' => 422, + 'description' => 'Unprocessable Entity', + ], + ], 422); + } + + // 429 Too Many Attempts + if ($e instanceof \Illuminate\Http\Exceptions\ThrottleRequestsException) { + return response()->json([ + 'result' => [ + 'status' => 'error', + 'code' => 429, + 'description' => 'Too Many Attempts.', + ], + ], 429); + } + } + + } +}