HTTP错误处理如何与可观察对象一起使用

HTTP错误处理如何与可观察对象一起使用

本文介绍了HTTP错误处理如何与可观察对象一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多教程都是这样的:

I see a lot of tutorials doing something like this:

http.get("...").subscribe(
  success => console.log('hello success'),
  error => console.log('bye error')
);

我不知道它是如何工作的,因为没有任何类型或任何内容,但是我有一个错误.有什么问题吗?

I don't know how this works, since there aren't any types or anything, however I tried to do that myself and I end up that the request always goes into success, even if I have an error. What is the problem?

麻烦制造者:

this.memberService.create(this.currentMember)
      .subscribe(
        success => {
          let mem: Member = success.json() as Member;
          if (this.selectedOrganization) {
            this.addMemberToOrganization(mem);
          } else if (this.selectedServiceProvider) {
            this.addMemberToServiceProvider(mem);
          } else {
            this.toastsService.error("lbl_users_service_provider_and_organization_undefined");
          }
        },
        error => console.log(error)
      );

memberService中的创建方法:

  create(member: Member): Observable<any> {
    return this.http
      .post(this.RESOURCE_BASE_URL, member)
      .map(response => {
        if (response.status === 200) this.toastsSerivce.success(this.translateService.instant('lbl_users_member_created'));
        return response;
      })
      .catch(error => this.toastsSerivce.error(this.translateService.instant('lbl_users_member_create_failed')));
  }

我什至抓住了错误,但是subscribe部分似乎不在乎.它在success.json()处失败,因为如果有错误,则没有json.但是,如果有错误,我希望它调用error =>...而不是success.任何建议都将受到高度赞赏.

I even catch the error, but the subscribe part doesn't seem to care.It fails at success.json(), because if there is an error, there is no json. But if there is an error, I want it to call the error =>... instead of the success. Any advice is highly appreciated.

推荐答案

我认为问题是您不是throwing错误,而是Observable.throw(errMsg).

因此,您可以像这样使用它:

So, you may just use it like this:

.catch((error:any) => Observable.throw(error.json().error || 'Server error'));

在您的示例中:

create(member: Member): Observable<any> {
    return this.http
      .post(this.RESOURCE_BASE_URL, member)
      .map(response => {
        if (response.status === 200) this.toastsSerivce.success(this.translateService.instant('lbl_users_member_created'));
        return response;
      })
      .catch((error:any) => Observable.throw(this.toastsSerivce.error(this.translateService.instant('lbl_users_member_create_failed'))));
  }

但是,您可以使用错误处理程序,例如Angular提出的错误处理程序此处:

But, you could use an error handler, like the one Angular proposes here:

private handleError (error: Response | any) {
    // In a real world app, you might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

因此,您的方法将更像这样:

And so, your method would look more like this:

create(member: Member): Observable<any> {
    return this.http
      .post(this.RESOURCE_BASE_URL, member)
      .map(response => {
        if (response.status === 200) this.toastsSerivce.success(this.translateService.instant('lbl_users_member_created'));
        return response;
      })
      .catch(this.handleError);
  }

对于您可能在服务中创建的其他方法,它实际上更干净,更可重用.

It's actually cleaner and more reusable for other methods that you may create within your service.

我建议也使用一个响应处理程序,例如Angular开发人员使用的响应处理程序:this.extractData.

I would suggest to use also a response handler, like the one used by Angular's devs: this.extractData.

在错误处理方法中,您可以放置​​自己的自定义逻辑,具体取决于您要如何显示或处理错误.

Obviusly, inside the error handle method you can put your own custom logic, depends on how you want to show or handle the error.

注意::我没有测试您的代码,也没有测试我在此处发布的代码.但是我想展示/表达这个概念. 您应该抛出错误,以免每次都进入success .处理方式取决于您和您的应用.

NOTE: I did not test your code nor the code I posted here. But I wanted to show/express the concept. You should throw the error in order to not going into success everytime. How you handle it depends on you and your App.

这篇关于HTTP错误处理如何与可观察对象一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-25 22:28