Fetch - the wrong way
fetch in JavaScript is awesome.
But, you may have something like this sprinkled throughout your code:
const ...
For further actions, you may consider blocking this person and/or reporting abuse
Constructions like this one where logic is driven by exceptions is an anti-pattern. This should be avoided. Unwinding the call stack is costly (probably in all modern languages).
Friends don't let friends use errors for flow control 👍
Can you explain a bit better, I don't understand what you are trying to say. How else would you handle each response status?
An HTTP response is just that, a response coming from the wire. Its status code is meaningless and its interpretation is given by the receptor. By itself, status code is just a number. There is no technical reason to raise an exception (throw an error) if a particular number is received.
This is particularly true when consuming RESTful API's. You may receive a 404 indicating the resource you're looking for is not found. Just because something isn't found we need to throw an error? Hell no.
+1 for Wretch :) For anyone evaluating options, there's github.com/sindresorhus/ky which is a similar wrapper too.
very nice post, + 1 follower
Excelente. Gracias
A good explanation around fetching and posting data
Great Post
Thanks for the great post!
I have a question about this sentence.
Is there any problem with the code of using Error.prototype.cause?
Below is a sample code.
So I frankly like this solution, and even made a video suggesting it, but some believe it is an anti pattern so I suggested to use a custom Error subclass in this post instead. I think jury is out if it’s wrong to use the cause property for things that aren’t errors
Thanks for your reply!
What points and reasons do they believe it is an anti-pattern?
The idea is that
cause
is supposed to be used for anError
, like described here v8.dev/features/error-cause, as it's main intent is when an error with acause
is thrown, the original error stack trace is printed along with itNow, in JS, technically you can
throw
anything, likethrow 'hello'
orthrow 1234
but it's pretty heavily discouraged. Some replies to my video pointed out that because you can throw anything, thecause
property must allow anything, but it similarly is best used for only error instances. Plus the benefit of errors in JS is that you can put any properties you want on them, likeerror.response
or whatever, so I thought that was a fair suggestion to use that just to be safe and stick to continuing to usecause
just for actual errorsI think this all depends a bit on how browsers handle visualizing error causes though, which I have not played with in detail myself, so I think time will really tell on what the best patterns actually are here
Nice article
Nice post.
A js alternative which i find simpler to use:
a
fetchXyz()
function which returns an object like:{ result, error }
where
error
could be a simple string.Then you use it like: