Skip to main content

Handling AuthorizationException Globally

Premium
6 min read

We continue shortening the OrderController, and now I want to remove the try-catch with AuthorizationException.

app/Http/Controllers/Api/V1/OrderController.php

public function show(Order $order)
{
try {
$this->isAble('view', $order); // policy
 
// ...
 
return new OrderResource($order);
} catch (AuthorizationException $eAuthorizationException) {
return $this->responseNotAuthorized();
}
}

There is no need to do this manually in every Controller method. That Exception can also be handled automatically by Laravel.


Controller Cleanup

So, we will remove this try-catch in THREE methods of this Controller.

BEFORE:

app/Http/Controllers/Api/V1/OrderController.php

class OrderController extends ApiController
{
// ...
 
public function show(Order $order)
{
try {
$this->isAble('view', $order); // policy
 
if ($this->include('user')) {
$order->load('user');
}
 
$order->load('products');
 
return new OrderResource($order);
} catch (AuthorizationException $eAuthorizationException) {
return $this->responseNotAuthorized();
}
}
 
public function update(UpdateOrderRequest $request, Order $order)
{
try {
$this->isAble('update', $order); // policy
$this->orderService->updateOrderHandleProducts($request, $order);
 
return response()->json(new OrderResource($order), Response::HTTP_OK);
} catch (AuthorizationException $eAuthorizationException) {
return $this->responseNotAuthorized();
} catch (QueryException $eQueryException) {
DB::rollback(); // Rollback transaction on database error
 
return $this->responseDbError();
} catch (Throwable $eTh) {
DB::rollback(); // Rollback transaction on any other error
 
return $this->responseUnexpectedError();
}
}
 
public function destroy(Order $order)
{
try {
$this->isAble('delete', $order); // policy
$this->orderService->deleteOrderHandleProducts($order);
 
return $this->responseSuccess('Order deleted successfully');
} catch (AuthorizationException $eAuthorizationException) {
return $this->responseNotAuthorized();
}
}
}

AFTER:

The Full Lesson is Only for Premium Members

Want to access all of our courses? (30 h 09 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.