From ba7e52f8acc534e5a4a09fdd3e0a7d8881ae989a Mon Sep 17 00:00:00 2001 From: Leonid Nikitin Date: Wed, 12 Jul 2023 23:44:53 +0600 Subject: [PATCH] Added a new function 'errors' in Private Controller to handle service errors. This function checks if the resulted error code matches HTTP_UNPROCESSABLE_ENTITY and in that case, it redirects back with input and errors. For any other case, it aborts with the resulted error code and message. The main purpose of this change is to centralize error handling in one place and make the controller's actions cleaner. --- app/Http/Controllers/Private/Controller.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/app/Http/Controllers/Private/Controller.php b/app/Http/Controllers/Private/Controller.php index 0d678f1..8ec4fd7 100644 --- a/app/Http/Controllers/Private/Controller.php +++ b/app/Http/Controllers/Private/Controller.php @@ -2,12 +2,23 @@ namespace App\Http\Controllers\Private; +use App\Contracts\ServiceResultError as ServiceResultErrorContract; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Validation\ValidatesRequests; +use Illuminate\Http\Response; use Illuminate\Routing\Controller as BaseController; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; + + final protected function errors(ServiceResultErrorContract $result): never + { + if ($result->getCode() === Response::HTTP_UNPROCESSABLE_ENTITY) { + redirect()->back()->withInput()->withErrors($result->getErrors()); + exit; + } + abort($result->getCode(), $result->getMessage()); + } }