Link to the repository
[Only for premium members]
[Only for premium members]
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.
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...