King Of Missionary
King Of Missionary

Reputation: 149

Error handling in Async Await API calling

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!

Upvotes: 3

Views: 4553

Answers (3)

Kai021195
Kai021195

Reputation: 833

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);
  }

Upvotes: 0

King Of Missionary
King Of Missionary

Reputation: 149

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)
  }
}

Upvotes: 1

Matt
Matt

Reputation: 1156

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);
  }
}

Upvotes: 1

Related Questions