http.get - 如何正确捕获 404

http.get - how to properly catch a 404

我正在构建一个日历应用程序,它每天从(当前模拟的)后端获取数据。 在 http.get 的正确 urls 上,这工作得很好,但如果 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 object) 而不是日历中的那一天什么都不显示。

您的问题在线

const body = error.json() || '';

问题在于,当您的后端发送错误(此处为 404)时,您不会发送 JSON 对象。所以如果你使用 error.json(),不要指望得到一个 JSON 对象!

您可能 return 来自后端的 JSON 错误,或者您没有在错误处理程序中使用 json() 函数。

当您不使用 json() 函数时,您还可以访问包含错误代码的 status 属性(如果我没记错的话就是这个)。所以你可以给它加上条件,比如如果它是 404,你就做你想做的。

我希望我说清楚了,如果没有,请随时询问更多细节!