Dan D Kim

Let's share stories

Simulating bad requests

2019-11-25 Dan D. Kimdebugging

I recently found out that you can block network requests on the Chrome Devtools. I think it’s pretty neat and want to share it.

What?

Blocking network requests is a way to simulate network errors on specified urls or domains.

Why?

Easily simulate network errors to debug and simulate certain error cases on your webapp.

Is this the ONLY way to simulate errors? Definitely not. It is the most proper? No. But it’s certainly a quick and easy way.

How?

  1. On your browser, press F12
  2. Options - On windows, it’s the 3 vertical dots.
  3. More tools -> Request blocking
  4. Add urls / domains to block.

Useful scenario example

Let’s say you had the following block of code that fetched front-page posts from reddit:

// Fetch Reddit post on the front page and display them
const redditResponse = await fetchRedditFrontPage()
displayPosts(redditResponse)

Let’s state that fetchRedditFrontPage() can fail due to 3rd party errors. This means we wrap it in a try catch.

try {
  const redditResponse = await fetchRedditFrontPage()
  displayPosts(redditResponse)
} catch (err) {
  displayError(err)
}

Here is a BEAUTIFUL mockup that I came up with:

My beautiful demo webapp

I’m able to see what happens when the code inside my try succeeds. But what if it fails? How should I validate the code in the catch block?

Maybe I could throw a manual error in the code…

try {
  throw new Error('uh oh')
  // const redditResponse = await fetchRedditFrontPage()
  // displayPosts(redditResponse)
} catch (err) {
  displayError(err)
}

This works, but I have to change the code. Changing the code may not be ideal in apps with large codebases. If there are multiple components that need to be tested, you may end up making multiple changes to the code. The application will also need to be reloaded.

Throwing new error vs having proper testing environments

Another way to simulate the error would be to use your DevTools! I will show how with Chrome:

Go to F12 -> Network then F5 refresh the page.

You will see the network call that is made to your localhost.

Network call made to localhost

Right-click on the network and select Block request URL

Blocking request url using chrome devtools

Note: Block request domain works too.

Now, I am able to properly test my catch without changing my code, and I can validate that my error cases are perfectly well-done.

blocked

That’s all. Happy debugging!