Skip to main content

OrderController with no try-catch: Final Version

Premium
10 min read

In this lesson, we will finalize our big goal of shortening the OrderController and removing the other try-catch methods.

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

public function store(StoreOrderRequest $request)
{
Gate::authorize('create', Order::class);
 
try {
$order = $this->orderService->createOrderHandleProducts($request);
 
return response()->json(new OrderResource($order), Response::HTTP_CREATED);
} 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 update(UpdateOrderRequest $request, Order $order)
{
Gate::authorize('update', $order);
 
try {
$this->orderService->updateOrderHandleProducts($request, $order);
 
return response()->json(new OrderResource($order), Response::HTTP_OK);
} 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();
}
}

Those try-catch blocks "clutter" the Controller, trying to catch Exceptions, which we can move to the bootstrap/app.php, like we did in the previous lessons with 404 and 403 status code Exceptions.

As a result, I hope to also entirely eliminate two Trait methods: responseDbError() and responseUnexpectedError(). Or maybe even remove that Trait altogether. We'll see.


Exceptions from Controller to bootstrap/app.php File

First, let's remove those from the Controller.

The methods are simplified to just THIS:

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

public function store(StoreOrderRequest $request)
{
Gate::authorize('create', Order::class);
 
$order = $this->orderService->createOrderHandleProducts($request);
 
return response()->json(new OrderResource($order), Response::HTTP_CREATED);
}
 
public function update(UpdateOrderRequest $request, Order $order)
{
Gate::authorize('update', $order);
 
$this->orderService->updateOrderHandleProducts($request, $order);
 
return response()->json(new OrderResource($order), Response::HTTP_OK);
}

Then, we handle those Exceptions in the same...

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.