【发布时间】:2017-12-04 02:45:02
【问题描述】:
我正在构建一个日历应用程序,该应用程序从(当前模拟的)后端获取每天的数据。 在 http.get 的正确 url 上,这工作得很好,但如果 url 错误,或者后端没有请求日期的 data/json 对象(例如,周末没有任何数据),我(显然)得到一个 404,虽然控制台中的日志很少显示它,但它总是给我以下错误:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
显然它不能有预期的字符,因为在请求的日期不存在 Json 对象。检查网络分析显示它确实是一个 404 错误。
我从这里使用基本的 http.get 和 handleError https://angular.io/guide/http#subscribe
带有http.get的服务代码:
getDayInfo(date: string): Observable<any> {
return this.gttp.get('somepath/' + date + '/somemoreinfo')
.map(this.extractData, // works just fine
console.log('map running for date: ', date)
)
.catch(this.handleError);
}
private extractData(res: Response) {
if (res != null) {
let body = res.json();;
return body;
} else { // else return an empty dummy json, doesn't really work here
return '[{"id": "", "userId": "", "userName": "", "type": { "name": "" }, "date": {' +
'"startDate": "", "endDate": "", "startTime": "", "endTime": "" } }]'; }
}
private handleError(error: Response | any) {
console.log('Errorhandling triggered');
let errMsg: string;
if (error instanceof Response) {
console.log('Errorhandling if-block'); // this triggers on a 404
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('Error ', errMsg); // this never appears in the log though
return Observable.throw(errMsg);
}
我的目标是捕获 404,而不是让它抛出我之前发布的 JSON.parse 错误,并通过发送一个空的 json 对象(或虚拟 json 对象)来处理它,以便日历中的日期只显示没有。
【问题讨论】:
标签: angular http error-handling http-status-code-404