Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get error message from Angular 2 http

Tags:

http

angular

I have the following code in my service

myService.ts

makeHttpGetRequest(url){

        return Observable.interval(config.SUPERVISOR_REFRESH_INTERVAL * 1000)
            .switchMap(() => this.http.get(url))
            .map(res => res.json())
            .timeout(config.REQUEST_TIMEOUT * 1000, new Error('Time out occurred'))

    }

In my component file,

myComponent.ts

ngOnInit(){
        this._myService.makeHttpGetRequest(myurl)
            .subscribe(
                data => {
                    this.supervisorServers = data;
                    }

                },
                error => {
                    this.error = true;
                    console.log(error); //gives an object at this point
                    this.showError(error);
                }
            );
    }

I want to print the error message in case of for e.g. Invailid url. When I print the error, I get an object (probably response object) like the following:

Object { _body: error, status: 200, statusText: "Ok", headers: Object, type: 3, url: null }

If I open this, I cannot find the error message. Is there a better way to get precies error messages?

like image 722
kosta Avatar asked Feb 27 '16 11:02

kosta


2 Answers

The error is contained in the body of the response even in this case. See the error event handler onError function:

  • https://github.com/angular/angular/blob/master/modules/@angular/http/src/backends/xhr_backend.ts#L96

You can access it using the json method on the response:

error => {
  this.error = true;
  console.log(error.json()); //gives the object object
  this.showError(error.json());
}

Edit

I investigated a bit more this issue. In fact, you can't have the exact message. I mean the net::ERR_NAME_NOT_RESOLVED. XHR doesn't provide it. That said, you can see that the status of XHR is 0. This could be an hint that there was a problem the request when sending the request (it's not actually sent).

error => {
  (...)
  var err = error.json();
  var status = err.currentTarget.status;
  (...)
}

See this question:

  • XMLHttpRequest() & net::ERR_NAME_NOT_RESOLVED
like image 84
Thierry Templier Avatar answered Oct 19 '22 12:10

Thierry Templier


I try error.error and work to me. Its get the Object message error.

EDIT:

Sorry!!

Try this:

            error => {
                this.error = true;
                console.log(error.error); 
                this.showError(error.error);
            }
like image 39
Jessica Rocha Avatar answered Oct 19 '22 11:10

Jessica Rocha