Http.post check error when server dose not response.(Сrashed)


#1

Hi all ! Could anyone suggest please, how to check situation when apache crashed or another server for example ? How to handle such an error ? It dose not working …

return new Promise((resolve, reject) => {
  const data = JSON.stringify({u: user.username, p: user.password });
  this.http.post(this.actions.login, data).subscribe(data => {
    resolve(data.json()),
    err => this.logError(err),
    () => console.log('Fetching complete for Server Metrics')
  },
    err => {
      console.log("ERROR!: ", err);
    }
  )
})

logError(err){
console.log(“some error”);
console.log(err);
}


#2

You can add this function to handle timeout :

this.http.post(this.actions.login, data).timeout(3003, new Error('Timeout')).subscribe(data => {
...});

#3

ArnaudDev, good day! Can we do something after timeout ? If for example we do not have response 20 second, show error message ?


#4

I think so, you throw a specific error (timeout), in the error function you can maybe test it ?

  err => {
    if (err == 'timeout') {
      //show alert for timeout
    }
    else {
      console.log("ERROR!: ", err);
    }
  }

#5

be careful, you must import

import 'rxjs/add/operator/timeout';

or it won’t work :wink:


#6

ArnaudDev, I will try now !


#7

ArnaudDev, It is working, thanks a lot !


#8

ArnaudDev, a little question… could be such kind mistake ?

Property 'timeout' does not exist on type 'Promise<any>'.


#9

yes this function (timeout) is only available for observable not promise


#10

ArnaudDev, I can not use timeout in such kind code ?

  Update(model_ext, include, data, iter, ext_id, page):Promise<any> {
    return new Promise((resolve, reject)=> {

    })
  }

Not exist other way check server crashed ?


#11

Why are you explicitly instantiating a promise?


#12

rapropos, to use function Update as promise with .then.


#13

You already have a perfectly serviceable Observable that Angular’s Http service has given you, that has error-handling capabilities that apparently do what you want to do. Just work with that. Don’t create needless Promises. I know that you see this code idiom all over the forums and web searches, but it’s bad, for many reasons. One major one is particularly relevant here: it doesn’t propagate errors properly.


#14

rapropos, thanks for answer, but I don’t understand what I need to do with my code to catch crashed server.