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

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

import axios from 'axios'const fetchTodos = async () => {
try {
const resp = await axios.get('');
} catch (err) {
// error handling

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!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gabriel Castro

Full Stack, Software Engineer. Focus in Rails, JavaScript and React.