-2

I get some data from server with Angular 2 Observable lib. The issue is that I want to handle all server statuses ( 200,404,500 ) and now show error in console.

return http.get( url, {headers})
      .map(res => res.json())
      .subscribe((res: any) => {
          console.log(res);
      }, (error: any) => {
         console.log(error);
         console.log('error finding variety list');
      });
Arayik
  • 114
  • 2
  • 10

1 Answers1

0

To get the status of your response, you can do this way :

return http.get( url, {headers})
.map(res => {
    // use res.status, here case if status is unauthorized
    if(res.status === 401) {
      throw new Error('Error unauthorized');
    }
    // case with no error
    else {
      return res.json();
    }
 })
.subscribe((res: any) =>
 {
     console.log(res);
 }, (error: any) => {
     console.log(error);
     console.log('error finding variety list');
 });
br.julien
  • 3,420
  • 2
  • 23
  • 44
  • The problem is that I can handle that errors. But I want to not show it in console. Because in this way I handle that but also I get error line in console. – Arayik Oct 30 '17 at 14:00
  • You don't need to have console.log(error); so if this is the problem, just delete this part. If the problem is that it prints anyway in the console, I think you should check this post : https://stackoverflow.com/questions/24207143/angular-avoid-console-trace-on-http-error – br.julien Oct 30 '17 at 14:06
  • Yes . The problem is that it prints anyway in console . And I want to control my code and don't show there errors – Arayik Oct 30 '17 at 14:20
  • It's not your Angular app that prints the error, the browser does it. So what you could do instead is to send a response with status=200 from your server side and create your own error inside the body of the response. Then handle the response according to the body – br.julien Oct 30 '17 at 14:40