2017-12-24 17 views
1

は、私は時々、このエラーを取得API呼び出しがあります。私のコードでHttpErrorResponseのインスタンスが、HttpClientを使用してAngularでサーバーレスポンスのサブスクリプションのエラー関数をトリガーしないのはなぜですか?

HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …} error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}message: "Http failure response for (unknown url): 0 Unknown Error"name: "HttpErrorResponse"ok: falsestatus: 0statusText: "Unknown Error"url: null } 

を、サーバーの呼び出しがそうのように扱われている...(免責事項、いくつかのコードは、簡潔のために簡単なバージョンに縮小されています)

import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 

getData() { 
    const apiRoot = 'http://whatever.../getSomething...'; 
    const params = new HttpParams().set('foo', 'bar'); 
    const body = { params }; 
    return this.http.get(apiRoot, body) 
     .map(res => res) 
     .catch(err => Observable.of(err)); 
} 

サーバの応答がそのように好きに加入している...

this.getData().subscribe(
    response => { 
     this.setApiResultsData(response); 
     console.log(response); // <-- where the "error" is printed 
    }, 
    error => { 
     this.setApiResultsError(error.message); 
     console.log(response); // <-- where I would think the error would go is never triggered... ??? 
    } 
); 

私の質問は、なぜそれをSにerrorに渡されませんされてubscription?私は何か間違っているのですか?

.catch(err => Observable.of(err)); 

したがって、呼び出し方法がない:あなたは、本質的にそれをキャッチし、新しい観測可能を返すことによって、エラーから回復している私は、正しくエラーを処理したいと思いますので、私はgetDataインサイド提案

答えて

1

に開いています長いとエラーが表示されます。あなたは、エラーをキャッチして投げることができ、新たな1:

getData() { 
    // ... 

    return this.http.get(apiRoot, body) 
     .map(res => res) 
     .catch(err => Observable.throw(err)); 
} 

それとも元のエラーが伝播するので、あなたは、getData内部からcatchを削除することができます:応答があり

getData() { 
    // ... 

    return this.http.get(apiRoot, body) 
     .map(res => res); 
} 
1

ほとんどのため、この場合、Angularはstatusをゼロとみなしてエラーにはなりません。 common/http/src/xhr.tsのコードを参照してください。

// Normalize another potential bug (this one comes from CORS). 
if (status === 0) { 
    status = !!body ? 200 : 0; 
} 
+0

ああ、完璧な意味があります。ありがとう。それはCORSの問題でもありますが、なぜ0のステータスコードがエラーではないのかが明確ではありませんでした。 –

関連する問題