【问题标题】:http.get - how to properly catch a 404http.get - 如何正确捕获 404
【发布时间】: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


    【解决方案1】:

    你的问题就出来了

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

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

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

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

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

    【讨论】:

    • 我直接从 Angular.io 中获取了我的 handleError 函数的那一部分,我认为它会很好......将在该领域进行一些实验。
    • 是的,我刚开始时也是这样做的,但是您必须考虑到响应高度依赖于您的后端,并且(至少对我而言)您很少考虑发送 json发生错误时的对象。
    • 似乎在测试 error.status 作为字符串工作,所以我似乎能够在此处捕获它并在我的组件中进一步处理它。在这一点上,我相信这将是我需要的解决方案,所以非常感谢
    • 试试console.log(error) 看看你也可以使用哪些字段。不用担心,它既不是修复也不是解决方法,响应对象本来就是要这样使用的,你会看到它们甚至有一个_body,这实际上是@987654328 返回的(作为JSON) @函数
    猜你喜欢
    • 2019-12-30
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多