6

I am sending request with fetch api and make action according to the result is correct or it includes error.

my service code:

LoginUser(user: User) {
    return fetch("http://localhost:8080/login", {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      method: 'POST',
      body: JSON.stringify(user)
    });
  }

and my then-catch code which calls the above one is:

async loginUser() {
  let response = await this._service.LoginUser(this.user)
  .then(response => {return response.json()})
  .then(response => {this._router.navigate(['/mainpage'])})
  .catch(error => {alert(error)});
 }

Whether the response is coming with code 500 Internal Server Error still it is redirecting to /mainpage and does not recognise the error. How can I fix this problem ?

Chris Garsonn
  • 717
  • 2
  • 18
  • 32

2 Answers2

10

When a fetch request comes back with an error code from the server, the catch of the promise is not executed, the then is. The catch is only executed if there is a network failure. See the fetch docs:

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

What you need to do is, inside your then, check response.ok. If response.ok == false, then the request returned an error. You can find info about this error in response.status and response.statusText.

ACarter
  • 5,688
  • 9
  • 39
  • 56
2

If you are using async await you shouldnt have to chain on .thens like you are resolving a promise.

I adjusted your code and wrapped it in a try/catch, the try/catch error will handle an error from a non response however you will need to check your server response for errors itself

async loginUser() {

    try {
        let response = await this._service.LoginUser(this.user)

        // Check your response for error this may not be response.error
        if (response.error) {
            // Handle error
            alert(error)
        } else {
            // Navigate on success
            this._router.navigate(['/mainpage'])
        }
    } catch (err) {
        alert(err)
    }
}
Jason McFarlane
  • 2,048
  • 3
  • 18
  • 30