为什么HttpErrorResponse的实例不使用HttpClient触发Angular中服务器响应的订阅的错误函数?

时间:2017-12-24 01:40:36

标签: angular http typescript rxjs

我有一个API调用,有时会出现此错误:

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... ???
    }
);

我的问题是,为什么它不会传递给订阅中的error?难道我做错了什么?我想正确处理错误,所以我愿意接受建议

2 个答案:

答案 0 :(得分:1)

getData内部,您实际上是通过捕获它并返回一个新的observable来从错误中恢复:

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

因此调用方法不再出现错误。您可以捕获错误并抛出一个新错误:

getData() {
    // ...

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

或者您可以从catch内删除getData,因此原始错误会传播:

getData() {
    // ...

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

答案 1 :(得分:1)

最可能的原因是响应有一个正文 - 在这种情况下,Angular不会将 for(i=5; i<8; i++) { JOptionPane.showInputDialog(null, "Search result: " + count + "\n" + "=======================\n" + "Country: " + country[i] + "\n" + "Month: " + travelmonth[i] + "\n" + "Description: " + description[i] + "\n" + "Price: $" + price[i] + "\n" + "=======================\n" + "Enter M to return to main menu"); count++; } } while(!inChoice.equalsIgnoreCase("M")); } 的零视为错误。请参阅common/http/src/xhr.ts中的以下代码:

status