4

I have an arrow function which returns some data from an api call. i want to wrap it up inside a try catch block like

const fetchEmployees = () => (
   try{
       fetch('http://localhost:6873/api/values', {
          method: 'GET',
          headers: {
            'content-type': 'application/json'
          }
       })
         .then(response => response.json())
         .then(names => { return names })
       } catch (error) {
           return error;
       }
  )

How could i do that? The perfectly working arrow function I have is

const fetchEmployees = () => (
fetch('http://localhost:6873/api/values', {
    method: 'GET',
    headers: {
        'content-type': 'application/json'
    }
})
    .then(response => response.json())
    .then(names => names )
)
Raihan Ridoy
  • 678
  • 8
  • 18

3 Answers3

3

You can't use try catch on fetch because fetch is async while try catch is sync. Therefore your try catch will always pass. if we assume that you received response, and .json() fails, in second then first parameter is success function second one is fail function that executes when .json() fails

const fetchEmployees = () => (
  fetch('http://localhost:6873/api/values', {
      method: 'GET',
      headers: {
          'content-type': 'application/json'
      }
  })
      .then(response => response.json())
      .then(names => names, error => "json failed" )
)

fetchEmployees().then(success => {}, error => {})

Like this when you call fetchEmployees in first function will be executed if everything succeed, otherwise second will execute with error response, in this case hard coded string "json failed"

chriss
  • 669
  • 4
  • 9
2

Turn your function into an async one:

const fetchEmployees = async () => {
  try {
    const response = await fetch("http://localhost:6873/api/values", {
      method: "GET",
      headers: {
        "content-type": "application/json"
      }
    });

    const names = await response.json();

    return names;
  } catch (error) {
    return error;
  }
};
nem035
  • 34,790
  • 6
  • 87
  • 99
1

Try to use async/await

const fetchEmployees = async () => {
   try {
       let response = await fetch('http://localhost:6873/api/values', {
          method: 'GET',
          headers: {
            'content-type': 'application/json'
          }
       });
       let json = await response.json();   
       return json;    
   } catch (error) {
     return error
   }
}
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345