【问题标题】:"Unhandled rejection" error in Aurelia Fetch ClientAurelia Fetch Client 中的“未处理的拒绝”错误
【发布时间】:2018-01-15 07:35:24
【问题描述】:

我使用 Aurelia Fetch Client 库通过代码从后端服务器获取 JSON 数据:

getData() {
    let httpClient = new HttpClient();

    return httpClient.fetch('http://localhost:9220/get-data')
        .then(response => response.json())
        .then(data => return data);
    }
}

而方法getData()是由代码从另一个代码中调用的:

dataService.getData().then(data => {
    this.data = data;
}).catch(error => {
    this.backendError = true;
});

如您所见,我在这里使用了 catch 语句,如果出现错误,则会调用它,但我还在控制台中看到来自库的错误消息:“vendor-bundle.js:1395未处理的拒绝类型错误:获取失败”。我怎样才能摆脱它?

【问题讨论】:

  • 由于您尝试调用的 API 失败,将导致该错误。
  • 是的,我知道,但是有什么方法可以处理这个错误吗?
  • 如果我的回答解决了您的问题 - 请将其标记为已接受。或者,如果没有,请告诉我,以便我进行相应的编辑。

标签: javascript fetch aurelia


【解决方案1】:

我不确定这是否是 Aurelia HTTP Fetch Client 的错误,但添加 responseError 拦截器应该会删除控制台中的未处理异常警告。

let http = new HttpClient();

http.configure(config => {
    config.withInterceptor({
        response(response) {
            return response;
        },
        responseError(error) {
            return error;
        }
    })
});

【讨论】:

    【解决方案2】:

    此错误也可能来自 .NET Core API 中的 UseDeveloperExceptionPage 中间件。此中间件从响应中删除所有导致 CORS 问题并导致您看到的“TypeError: Failed to fetch”错误的标头。这是我的解决方案的一个示例,完整描述了here

    .NET Core 中间件

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        var code = HttpStatusCode.InternalServerError;
    
        var result = JsonConvert.SerializeObject(new { error = "An internal server error has occurred." });
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)code;
        return context.Response.WriteAsync(result);
    }
    

    Aurelia 拦截器

    responseError(response: any): Promise<Response> {
        if (response instanceof Response) {
            return response.json().then((serverError: ServerError) => {
    
                 // Do something with the error here.
    
                 return Promise.reject<Response>(serverError.error);
            }); 
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 2017-01-20
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 2019-10-27
      相关资源
      最近更新 更多