Emulate Network Errors in MSW

Share this video with your friends

Social Share Links

Send Tweet
Published a year ago
Updated a year ago

Accounting for network errors is what makes a good application great. Unlike error responses, network errors represent issues when sending a request or receiving a response, but all the same can be mocked with standard JavaScript API.

In this lesson, you will learn about Response.error() and how to use it to emulate network errors in your Mock Service Worker handlers.

Instructor: [0:00] Being able to model any server response is powerful, but there is a whole area of network issues that are not caused by the server. What if the client loses the Internet connection, or the network provider fails to resolve the DNS record for the host or app requests? Depending on the product you're building, these network errors can have a different impact on your users.

[0:19] I still recommend accounting for them, at least to some degree, to build bulletproof UIs. The best part is that we can use the standard JavaScript API to reproduce network errors. To create a network error response, call the error static method on the Response class. Since HTTP response extends the standard response class, it also inherits the error static method.

[0:45] Note that network errors and server errors are quite different. A server error still represents a complete response from the server, only indicates a semantic problem while handling the request. This is the reason why the Fetch API doesn't reject the request promise when you get 400 or 500 responses.

[1:03] A network error, on the other hand, means a failed request, the kind that was aborted during processing, or that has never reached the server to begin with. As a result, network errors reject the pending request promise. Keep this difference in mind when handling these two kinds of errors.