简体   繁体   English

服务和控制器中的angular4错误处理

[英]angular4 error handling in service and controller

I have the following question: 我有以下问题:

I have a http post request in a service. 我在服务中有一个http发布请求。 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. 如果在php或mysql中生成错误,则将布尔值设置为true并显示一条消息。 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. 现在的问题是,仅当例如PHP后端关闭时,才在控制器中命中error =>,而不是在我从服务中抛出错误时才命中。

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, 谢谢,

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. 请注意,不建议使用Http服务。 You should switch to HttpClient. 您应该切换到HttpClient。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM