Error handling is crucial for a great user experience. Learn how to reproduce any error response with Mock Service Worker, be it a 404, 500, or any other HTTP error response.
Instructor: [0:05] When working on the UI that fetches data, we have to account for different network-related states such as error responses, latency, and connectivity issues. In our movie recommendations component, we want to display a user-friendly error message whenever fetching the recommendations fails. With MSW, we can reproduce any network state using request handlers.
[0:22] To respond to a request with an error, construct a valid response instance, and set its status property to reflect the server error you want. In our case, let's see how our UI handles a response with a 500 status code, which indicates a generic server error when handling this request.
[0:40] We've got our request handler pinned to always return an error response, which is handy while working on error handling in our application. Same as with successful responses, we can see this 500 response in the Network tab, in the browser's DevTools. To toggle between the success and error responses, we can return our 500 response conditionally.
[1:00] As an example, let's respond with an error only when fetching recommendations for a particular movie. With this condition in place, we can now check different states of the UI by opening different movies in the browser.
[1:13] You can utilize error responses to help you develop features or catch issues. For example, it's a good idea to check if the movieId query parameter has been sent by the client, and if it's missing, respond with a 400 response indicating a bad request and a JSON body describing what's wrong.