Part 20 - Handle errors in Show method [How to use TDD to build a REST API in Laravel 6]

Опубликовано: 16 Октябрь 2024
на канале: StudyStream+
146
0

Let’s handle errors in the Show method. Our endpoint accepts id as a parameter. If we don’t provide this parameter, the routing will send the request to the index method. We don’t have to worry about that. Let’s see what happens when we send an ID that does not exist.

Let’s open up our ShowCest file. There test can be called itWillReturn404WhenRecordCannotBeFound().

Let’s send a GET request with a random id. Run the test. Looks like we get back an HTML response. We can see in this response, the code is failing. Let’s make the test pass.

We need to open up our PostController and navigate to our show method. Inside the show method, we can wrap the code in a try catch block.

If we can’t find the record, we can throw an exception. So we need a response for the error.

Let’s run our test, it should pass and it does. Now have you noticed, we will be showing error responses in multiple places. Let’s refactor this line into its own method.

You might be wondering, why we are not writing a test first. It is because: the logic will be covered by our tests already. So let’s use PhpStorm to perform the refactoring for us. It will detect other code fragments for us too.

Remember to run your entire test suite. Everything passes.

Watch the next video here:
   • Part 21 - Handle errors in Index meth...  

Watch this course in full here:
   • How to use TDD to build a REST API in...  

Laravel Tutorials:
   • Laravel PHP Tutorials  

2 - 3 min Developer Quick Tips Series:
https://www.youtube.com/playlist?list... this course in full here:
   • How to use TDD to build a REST API in...