The main problem with
fetch function is that it isn't a generic function. This makes it harder to type response data without writing additional wrappers.
We can create a wrapper-module to avoid this problem.
Let's create a function
request that will handle network requests:
Now we can call this function as we would call
Or, since it is an
async function we can use
Right now the
request function doesn't handle errors. To solve that we have 2 options:
Handle errors inside of the
Let another module handle errors.
There are no obligatory rules for this but Single Responsibility Principle tells us not to mix those concerns in a single function.
However, we will take a look at both ways. The first one is to handle errors inside of the
We can use
catch to handle unresolved promises. There is a catch though (no pun intended).
We can pass incorrect arguments to
fetchand error will arise before the very first
We may even not know how to handle an error in
The first issue we can solve making the function
async and using
However, this doesn't solve the second issue with not knowing how to handle the error. We can handle some basic network errors (Page Not Found, Bad Request) but we cannot handle any business-logic errors.
async/await approach, we can handle errors outside of the
We can also pre-define some basic request-methods, like
We will use them like this:
fetchfunction is not generic.
To type the response result we need to create a wrapper generic-function ourselves.
We can handle errors in that same wrapper or outside. Either approach has pros and cons.
We can use
thenas well as
awaitwith Promise-based functions but
awaitis a bit more convenient when it comes to error handling.