Emulate Network Errors in MSW

Share this video with your friends

Social Share Links

Send Tweet
Published 7 months ago
Updated 6 months 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.

egghead
egghead
~ 10 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today