Average Joe
Average Joe

Reputation: 4601

detecting a 404 on a http get and quickly handling it

I got this HTTP get request:

this.httpService.getData ('http://example.com/wp-json/wp/v2/' + 'badReferenceHere').subscribe(
          (response: Response) => {
            let apiResponse = JSON.parse(JSON.stringify(response));
            this.post_content = apiResponse.content.rendered;
            // do something with the this.post_content
          },
          (error: any) => {
            this.post_content = 'An error has occurred.';
        });

If the URL is missing, and you already got a Failed to load resource: the server responded with a status of 404 (Not Found) message on the dev tools console.log, but yet, your code still showing the spinner, what are you supposed to do to quickly detect this and stop the wait and handle the 404 to say a message such as "That link does not exist"?

Upvotes: 0

Views: 136

Answers (2)

Vinod Bhavnani
Vinod Bhavnani

Reputation: 2225

You need to handle this in your error handler:

this.httpService.getData ('http://example.com/wp-json/wp/v2/' + 'badReferenceHere').subscribe(
      (response: Response) => {
        let apiResponse = JSON.parse(JSON.stringify(response));
        this.post_content = apiResponse.content.rendered;
        // do something with the this.post_content
      },
      (error: any) => {
        this.post_content = 'An error has occurred: ' + error.message ;
        alert(this.post_content);
        //Code to stop spinner
    });

Upvotes: 1

bhargav
bhargav

Reputation: 13

GetMethod(url): Observable<any> {
        return this._http.get(url, { body: "" })
            .map(res => <any>res.json());
    }

Upvotes: 1

Related Questions