2017-08-26 45 views
1

我使用一個HTTP API,通過一個JSON返回應用程序級錯誤,其中status =='error'。Angular 4:如何正確處理應用程序級http錯誤爲可觀察錯誤?

在我的註冊服務,我這樣做:

return this.userService 
     .create(user) 
     .map(
      json => { 
       console.log(json); 
       if (json.status=='error') { 
        console.log('error return throw'); 
        return Observable.throw('Credentials mismatch or not existing'); 
       } 

       const user = json.data as User;  
       return user; 
      }, 
      err => { 
       console.log(err); 
      } 
     ); 

在我singUp.component,我這樣做:

onSubmit() { 
     // blahblah 

     this.si 
     .signUp(this.credentials.emailAddress, this.credentials.password, this.credentials.zipCode) 
     .subscribe(
     user => { 
      console.log(user); 
      console.log(`SignUpComponent.onSubmit() found user.userId ${user.userId}`); 
      this.router.navigate(['signin']); 
     }, 
     err => { 
      this.errorMessage = `*** SignUpComponent: Error while signing up {err}`; 
      console.error('*** SignUpComponent: Error while signing up', err); 
      this.resume(); 
      //this.router.navigate(['signup']); 
     }); 

     this.ngOnChanges(); 
    } 

不幸的是,當服務返回錯誤(與可觀測.throw())時,組件不會觸發err閉包,而是會將用戶參數傳遞Observable.throw作爲用戶閉包。

我希望我有err關閉被觸發。

我缺少什麼?

更新:這是我所得到的:

[Log] SigninService.signUp, zipCode= 
[Log] {data: null, status: "error", message: "Error user create: - missing id API usage v1b3: Tu…ate\"}↵post: []↵.↵", ws: "v1b3: Tuesday, August 25th 2017 20h20 @ Tanger"} 
[Log] error return throw 
[Log] ErrorObservable {_isScalar: false, error: "Credentials mismatch or not existing", scheduler: undefined, _subscribe: function, …} 
[Log] SignUpComponent.onSubmit() found user.userId undefined 
+0

什麼是你'.MAP()'d卷板機? – Aravind

+0

它會查找API狀態以確保API返回全新用戶(當status =='success'時)。如果狀態等於「錯誤」(代表用戶帳戶未被創建),我希望我爲訂戶生成錯誤。 –

+0

這工作? – Aravind

回答

1

您正在處理用戶回調內的異常,這意味着它已被成功執行,在這種情況下,Observable.throws不會真正作爲例外。爲了實現這一點,您必須使用throw new Error("Credentials mismatch or not existing")必須替換return Observable.throw("Credentials mismatch or not existing");請看,看看這個:How to throw error from RxJS map operator (angular)

+0

感謝@dag讓我走上正軌。修改您的答案爲:拋出新的錯誤(「證書不匹配或不存在」);必須替換返回Observable.thow(「證書不匹配或不存在」);這樣我才能接受它。 –

0

爲了避免您遇到的問題,我想你只需要做throw 'Credentials mismatch or not existing'沒有回報可觀測部分。在執行observable期間產生的任何錯誤都會在當前的Observable上傳播爲錯誤。

目前,你只是用Observable替換json響應,這不是你想要的。

理想情況下,服務器應該返回錯誤響應而不是帶有錯誤消息的json,並且會觸發您在訂閱中的error處理程序。

+0

中加入了日誌,這是我第一次嘗試之前嘗試返回Observable.throw()在desesparate移動。 –

0

我終於想出了以下解決方案,擴展了1)用throw new Error()我仍然可以返回一個Observable和2)當錯誤拋出subscribe完成參數時不觸發,一個需要使用的最後()調用如下:

註冊服務:

create(user: User): Observable<User> { 
    const wsUrl = `${this.wsApi}m=create&id=${user.id}`; // URL to web api 

    return this.http.post(wsUrl, JSON.stringify(user), { headers: this.headers }) 
    .retry(3) 
    .map(res => { 
     const json = res.json() as any; 

     if (json.status=='error') throw new Error(json.message); 

     return json.data as User; 
    }); 
} 

註冊組件:

onSubmit() { 
     // blahblah 

     this.progressing = true; 

     this.si 
     .signUp(this.credentials.emailAddress, this.credentials.password, this.credentials.zipCode) 
     .finally(() => setTimeout(() => this.progressing = false, 1000)) 
     .subscribe(
      user => this.router.navigate(['signin']), 
      err => this.errorMessage = err 
     ); 

     this.ngOnChanges(); 
    }