Skip to main content

How to Simulate HTTP Request Errors

· 3 min read

Errors handling is part of our work as developers. You can try to ignore them at first, but to offer a good user experience, you don't want your website breaking just because one of the API endpoints decided to give up on you. These days we try to find clever workarounds to run our applications with a graceful degradation strategy. We build software to work in an optimal environment while providing certain fallbacks not to break the experience entirely when there's some disturbance in the system (e.g., lousy network condition, CPU lag, etc.).

In this article, we will understand how to maximize productivity when tackling HTTP requests error handling from a front-end development perspective.

Here's a web app we use to test our browser extension. If you click on the button "Get Characters Data" you should see text populating the below part of the section, simple.

"sample http request and display data"

Now, let's see what happens when for some reason, the server fails. But how do I go about simulating a server failure? Should I just wait for the backend to be down? If you have these questions, this article is for you. The answer is: with tweak, you can easily change an HTTP request and its status code with a few clicks. Here's how to set up the extension to simulate a failure.

"tweak setup http error simulation"

In this case, we're using the status code 500, but it's really up to you what kind of error you're trying to simulate here. Now we activate the extension, and we trigger the request once more.

"tweak error simulation in the browser"

Oh no! The UI is stuck in that loading state. Let's get back to work and catch this request failure to display a custom message.

(code noises)

(code noises)

... a few minutes later

Ok, after some coding, our application should be able to handle errors gracefully by displaying an error message in the UI. Let's see it in action and test the same flow with tweak.

"tweak gracefully error handling"

Awesome! Mission accomplished. In just a couple of minutes, we have:

  1. Simulated an API error in our UI to realize that the UI does not handle errors at all.
  2. We went back to code and handled the error.
  3. We reran the same workflow to trigger the error with the extension, but this time we see the UI behaving nicely and not getting stuck in an infinite loading state.

Why can't I simply use the browser request blocker to achieve this? The request blocker feature is great, but it's limited. You won't be able to set a custom status code, neither you'll be able to provide a response payload to simulate different server failure scenarios.

Want to give it a try? tweak is available for free in the chrome & firefox browsers. Just follow the links on the top of this website to install it.

If you liked this article, consider sharing (tweeting) it to your followers.

Did you like this article?