Now that we have our CRUD operations, we should check that basic functionality works as expected. In this case, we want to ensure we correctly handle 404
errors. Let's look at the default way:
We can do better than this.
Correctly Handling 404 Error
We tried to load a category with the ID of 123
with our first test but got a long message. This was because we have APP_DEBUG=true
in our .env
file. We can change this to APP_DEBUG=false
to see what we would get in a production environment:
It's better since we don't have the stack trace, but it's still not good enough. We are leaking information about our application (specifically, the model name and namespace). We can do better.
So, let's modify our Exception handler to handle this case:
bootstrap/app.php
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; // ... return Application::configure(basePath: dirname(__DIR__)) // ... ->withExceptions(function (Exceptions $exceptions) { $exceptions->renderable(function (NotFoundHttpException $e) { return response()->json(['message' => 'Resource you are looking for was not found.'], 404); }); })->create();
Now, when we try to load a category with an ID of 123
, we get a more user-friendly message:
This message can be customized further, but this is good enough for now.
Note: Other exceptions can be handled in the same way. Add another renderable
method with the Exception you want to handle.
In the next lesson, we will create a Transaction model and controller to handle transactions for our Categories.
Check out the GitHub Commit
No comments yet…