Workshop context
Before this workshop
- In previous workshops, we created a
statusstate and updated it to indicate a fetch in progress.
This workshop
- In this workshop, we’re going to handle the error cases for the fetch.
After this workshop
- In the next workshop, we’ll abstract the fetch and state logic into a custom hook .
Workshop goal
By the end of this workshop, your application will:
- Set the
statusstate to “error” if:- an error occurred during fetch
- the response is not ok
- the returned json does not have a
quoteproperty
- Store a string version of the error in a new state variable called
error.
Note: like the last workshop, there is no UI here. You’ll want to use console.log to examine the state for now.
Hints
Hint 2
You can capture the exception that was thrown with exceptionVar syntax . Conventionally, this exception variable is given the nameerror (see line 3 of this example ).Hint 3
Suppose you’ve usederror as the string for the exception variable (see previous hint). You can get the string version of the thrown exception within the catch block by using the toString() method : error.toString()Since the type of error is technically unknown, you’ll need to use optional chaining to satisfy TypeScript: error?.toString().
Hint 4
For theok and json parameter errors, you can throw an Error within the try block if either of those conditions is true. Once an error is thrown, the code in the try block will stop executing and the catch block will take over (using the thrown error as the exception).Resources
- MDN docs on try/catch
- MDN docs on throwing an Error
- MDN docs on the
Error.prototype.toString()method