Weightlifting Is A Waste Of Time Guide Review

This would not depend as a conviction if the additional time was to be served concurrently or if it solely changed the parole eligibility date . The only exception to this rule is for “Lifers,”…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Fetch API Errors and the Principle of Least Surprise

It’s possible that you still don’t know this:

I find myself explaining this during PRs and training sessions more often than not, so I thought that I might as well write it down. Newcomers and less experienced developers tend to struggle with this and there’s no reason to be ashamed.

You could have expected the /error/XXX requests to reject due to the server error, but that wasn’t the case. The test code rejected cause we tried to parse as JSON the response content using res.json(). Using res.text(), the call will be resolved to the Boom! string sent by the server as the error response body:

QED. As the spec says, fetch only rejects client errors. Server errors are considered successful requests, because, from the fetch point of view, they are: the server responded with the correct headers and a body, and the connection was closed cleanly 😅.

Completion or failure… 🤔.

I think the problem lies in the API and how it clashes with developer expectations. By returning a Promise, one would normally expect it to resolve when the fetch succeeds and to reject when it fails. A server error, in any mental model is usually a failure. Thus, by only treating client errors as failures, fetch surprises developers 😌.

Some languages, like Ruby, were designed with POLS in mind, and are approachable and a joy to work with. JavaScript is not one of those languages.

If you’ve read some of my other stories you already know. What I usually do is decorate fetch to make my own custom fetch function that behaves exactly as I (or anyone else would expect):

Using this our tests now behave as expected 🥰.

If you didn’t know this or if you have struggled in the past handling fetch errors, don’t be ashamed. You are not alone. It has surprised many developers for many years and will continue to do so.

Add a comment

Related posts:

The Gander

A poetic comment on the differential experiences of men and women under family law after separation and divorce, and the impact it can have on children.

How to Choose the Best Kitting Company

For the normal operations of various work, places can be achieved, and it is very much important to make sure the essential resources are present. At times combining the various resources as a…

A Christmas Fairytale

A miracle of Christmas in the Emergency Department. It’s shortly after midnight, and the cubicles are largely clear. A motley cohort of drunken misadventures, grizzly feverish kids and crumpled old…