From 361309af2902d65cb0b84e50724a2520f5ef9eaa Mon Sep 17 00:00:00 2001 From: Mohammad Alavi Date: Sat, 16 Apr 2022 13:11:20 +0430 Subject: [PATCH] refactor: improve exception handling --- .../User/UI/API/Tests/Functional/GetAllUsersTest.php | 2 +- app/Ship/Exceptions/Handlers/ExceptionsHandler.php | 12 ++++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/app/Containers/AppSection/User/UI/API/Tests/Functional/GetAllUsersTest.php b/app/Containers/AppSection/User/UI/API/Tests/Functional/GetAllUsersTest.php index 5f7043483..32383c00c 100644 --- a/app/Containers/AppSection/User/UI/API/Tests/Functional/GetAllUsersTest.php +++ b/app/Containers/AppSection/User/UI/API/Tests/Functional/GetAllUsersTest.php @@ -47,7 +47,7 @@ public function testGetAllUsersByNonAdmin(): void $response->assertJson( fn (AssertableJson $json) => $json->has('message') - ->where('message', 'This action is unauthorized.') + ->where('message', 'You are not authorized to request this resource.') ->etc() ); } diff --git a/app/Ship/Exceptions/Handlers/ExceptionsHandler.php b/app/Ship/Exceptions/Handlers/ExceptionsHandler.php index 0835b7103..e45393012 100644 --- a/app/Ship/Exceptions/Handlers/ExceptionsHandler.php +++ b/app/Ship/Exceptions/Handlers/ExceptionsHandler.php @@ -3,10 +3,13 @@ namespace App\Ship\Exceptions\Handlers; use Apiato\Core\Abstracts\Exceptions\Exception as CoreException; -use Apiato\Core\Exceptions\AuthenticationException; +use Apiato\Core\Exceptions\AuthenticationException as CoreAuthenticationException; use Apiato\Core\Exceptions\Handlers\ExceptionsHandler as CoreExceptionsHandler; +use App\Ship\Exceptions\NotAuthorizedResourceException; use App\Ship\Exceptions\NotFoundException; +use Illuminate\Auth\AuthenticationException as LaravelAuthenticationException; use Illuminate\Http\JsonResponse; +use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Throwable; @@ -57,7 +60,7 @@ public function register(): void }); $this->renderable(function (AccessDeniedHttpException $e) { - return $this->buildResponse(new AuthenticationException()); + return $this->buildResponse(new NotAuthorizedResourceException()); }); } @@ -81,4 +84,9 @@ private function buildResponse(CoreException $e): JsonResponse return response()->json($response, (int)$e->getCode()); } + + protected function unauthenticated($request, LaravelAuthenticationException $exception): JsonResponse|Response + { + return $this->buildResponse(new CoreAuthenticationException()); + } }