0

I have the following question:

I have a http post request in a service. The request returns a object:

export interface IResponse<T> {
    Error:boolean
    ErrorMessage:string
    Data:T
}

If an error is generated in either php or mysql the boolean is set to true with a message. The request from the service:

searchPersons(personSearchObject:PersonSearchObject){
    //generate request here
    return this.http.post(Config.ServerUrl, "data="+ request, options)
    .map( (responseData) => {
        this.personResponse = responseData.json()
        if (!this.personResponse.Error){
            this.persons.next(this.personResponse.Data)
            return;
        } else {
            console.log(this.personResponse.ErrorMessage)
            return Observable.throw(new Error(this.personResponse.ErrorMessage))
        }
    })
}

The request is called from the controller:

 this.personSearchService.searchPersons(personSearchObject).subscribe(
                result => {},
                error => { 
                    console.log("There was an error");
            })
        }

Now the problem is that the error=> in the controller is only hit when for example the php backend is down, not when I throw the error from the service.

How can I notify the controller that there was an error in the response from the request?

Other question is can I simply leave out the result in the controller, and only catch the error?

Thanks,

1
  • 1
    Everything would be so much easier if your backend, instead of returning a response with status 200 success, but a body indicating that there was in fact an error, respected the HTTP standard and returned an actual error response, with status 500 internal error. Why don't you do that? Commented Nov 3, 2017 at 8:01

1 Answer 1

1

You should definitely fix your backend, so that it returns actual error responses. But anyway, your code should rather be:

searchPersons(personSearchObject:PersonSearchObject) {
  return this.http.post(Config.ServerUrl, "data="+ request, options)
    .switchMap(response => {
      const personResponse = response.json()
      if (!personResponse.Error) {
        return Observable.of(personResponse.Data);
      } 
      else {
        return Observable.throw(new Error(personResponse.ErrorMessage));
      }
    });
}

Note that the Http service is deprecated. You should switch to HttpClient.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this. Exploring HTTPClient now, which raises another bunch of questions, but will continue to explore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.