Michaela Ervin
Michaela Ervin

Reputation: 740

Angular 4 async await uncaught exception in promise

I am always getting an error

ERROR Error: Uncaught (in promise): e: {"headers":{"normalize dNames":{},"lazyUpdate":null},"status":400,"statusText":"Bad Request"

code is: (updated)

async verify() {
  let schema = {"token": localStorage.getItem('id_token')};
  let response: any = await this.http.post('/api-token-verify/', schema).toPromise();
  return response;
}

public async tokenAliveState() {
  console.log("1");
  let stuff = await this.verify();
  console.log("2");

  console.log("Returning from tokenAliveState");
  return tokenNotExpired('id_token');
}

All I want to do is make a post and wait for the response before moving on. The response is plain JSON.

Angular core 4.

Any ideas? Any more info needed?

Does anyone have a working example of a simple function to wait on an http response before continuing execution? All the example I found online show similar to this but no matter what I do I get the uncaught exception.

Upvotes: 0

Views: 1164

Answers (2)

Akash Nigam
Akash Nigam

Reputation: 417

You should always wrap an await call in a try catch block and then handle it accordingly.

try {
    let response: any = await this.http.post('/api-token-verify/', schema).toPromise();
} catch (err) {
    // Handle the 400 http code here.
}

Upvotes: 1

Anjil Dhamala
Anjil Dhamala

Reputation: 1622

"stuff" is a promise. You need to .then() and .catch() the response/errors from the async call. Basically, your http call didn't go through and you did not catch the error returned from the promise.

stuff
  .then(() => {})
  .catch((error) => {}) 

should make your error go away.

Upvotes: 0

Related Questions