3

I have a script that uses node-fetch and is asynchronous when making fetch calls. I've tried to implement error handling, yet I have had no luck finding a solution. A snippet of my code is available below, and I need to find a way to detect when the API being called sends back an error.

var url = "https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=API KEY";
var payload = {
  email: email,
  password: password,
  returnSecureToken: true

};

 var options = {
     method: 'post',
     contentType: 'application/json',
     body: JSON.stringify(payload)
  };
    var res = await fetch(url, options);
  var result = await res.json();
response.send(JSON.stringify(result))

Thanks And I appreciate any attempt at resolving this issue!

DIllon marks
  • 59
  • 1
  • 6

3 Answers3

1

The following will work.

async function f() {

  try {
    let response = await fetch('/something');
    let user = await response.json();
  } catch(err) {
    // catches errors both in fetch and response.json
    alert(err);
  }
}
optimus_prime
  • 1,039
  • 2
  • 10
  • 21
1

I figured it out. Just check the response code.

async function helloWorld() {
    url ="someurl"
    let response = await fetch(url);
    let result = await response.json();
    if(response.status == 400){
    res.status(400).send(JSON.stringify(result)
  }
}
DIllon marks
  • 59
  • 1
  • 6
0

I had the same situation, and I found the answer in this article.

Handling error from async await syntax with axios

since like axios has updated this, this is how I do it.

try {
    const res = await publicRequest.post("/users/login",{email:email,password:password});
    console.log(res);
    setIsLoading(false);
  } catch (error:any) {
    console.log(error.response.data.error)
    setError(error.response.data.error);
    setIsLoading(false);
  }
Dharman
  • 30,962
  • 25
  • 85
  • 135
Kai021195
  • 653
  • 3
  • 13
  • 26