http.get - 如何正确捕获 404

m41*_*41n 4 error-handling http http-status-code-404 angular

我正在构建一个日历应用程序,它从(当前模拟的)后端获取每天的数据。在 http.get 的正确 url 上,这可以正常工作,但如果 url 错误,或者请求的一天后端没有 data/json 对象(例如,周末没有任何数据),我(显然)得到 404,尽管控制台中的日志很少显示它,但它总是给我以下错误:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Run Code Online (Sandbox Code Playgroud)

显然它不能有预期的字符,因为请求的日期不存在 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);
}
Run Code Online (Sandbox Code Playgroud)

我的目标是捕获 404 而不是让它抛出我之前发布的 JSON.parse 错误,而是通过发送一个空的 json 对象(或一个虚拟的 json 对象)来处理它,这样日历中的一天就不会显示任何内容。

小智 5

你的问题上线了

const body = error.json() || '';
Run Code Online (Sandbox Code Playgroud)

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

要么从后端返回 JSON 错误,要么不在json()错误处理程序中使用该函数。

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

我想我已经说清楚了,如果没有,请随时询问更多详细信息!