Try and Catch
Last week I got into Axios, how to get started and how it can be used to improve our fetch requests. This week I thought I would expand upon this a little bit and look at how we can UP our promise game by adding error handling with try and catch.
Try and Catch
So what is try and catch? well its just like it sounds!
try {
//axios.get .....
} catch (error) {
//error handling ...
}
First, with our try block we are executing our fetch call, in this case axios. If this axios call is successful then the code continues, in our example it would just skip the error handling and return the desired result. However, if the try block is executed and error happens, the catch (error) block will halt the code and return the error. To ensure that try and catch (error) block run it needs to be valid JavaScript or else all is for not.
Real World
Alright, so now we got an idea of how this works….lets see it in a real world example.
import axios from 'axios'const fetchTodos = async () => {
try {
const resp = await axios.get('https://jsonplaceholder.typicode.com/todos');
console.log(resp.data);
} catch (err) {
// error handling
console.error(error);
}
};
fetchTodos();
Lets break it down a bit, again we are using async await with axios to keep our promise a little cleaner, but now we are adding on our try and catch block. In this case we are returning jsonplaceholder/todos.
If there was an error it would be returned in our console.
Happy Coding!