Search code examples
javascriptangulartypescriptfetch-api

How to catch the error when making fetch api request?


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 ?


Solution

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