DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

try..catch..finally - Real example

const getData = async () => {
  try {
    setLoading(true);
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/posts"
    );
    // if error occurs here, then all the statements 
    //in the try block below this wont run.
    // Hence cannot turn off loading here.
    const data = await response.json();
    setData(data);
  } catch (error) {
    console.log(error);
    setToastMessage(error);
  } finally {
    setLoading(false); // Turn off loading irrespective of the status.
  }
};

getData();
Enter fullscreen mode Exit fullscreen mode

Thanks for reading πŸ’™

Follow @codedrops.tech for daily posts.

Instagram ● Twitter ● Facebook

Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript

codedrops.tech

Top comments (5)

Collapse
 
dkodeit profile image
dkodeit

Example is missing some important information...

The fetch API does not 'throw' errors, so this example is not 'catching' anything.

if (!response.ok) { throw Error(response.statusText) }

From the docs:
A fetch() promise only rejects when a network error is encountered (which is usually when there’s a permissions issue or similar). A fetch() promise does not reject on HTTP errors (404, etc.). Instead, a then() handler must check the Response.ok and/or Response.status properties.

Collapse
 
bias profile image
Tobias Nickel

and what do you need finally for?

Collapse
 
ml318097 profile image
Mehul Lakhanpal

In finally block you can perform things in all the cases. An error occurs or not the finally is executed. Ex., Turn off loading.

Collapse
 
bias profile image
Tobias Nickel

yes, but you actually don't need the finally block for that. you can call setLoading(false) directly below the catch block.

do you think it looks just better? or is more clear?

Thread Thread
 
ml318097 profile image
Mehul Lakhanpal

You need it in try also then. And btw just an example. What if you need to execute more than 1 statement after the process. I cant copy paste in both try and catch block.