簡體   English   中英

Aurelia Fetch Client中的“未處理的拒絕”錯誤

[英]“Unhandled rejection” error in Aurelia Fetch Client

我使用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未處理的拒絕TypeError:無法獲取 ” 。 我該如何擺脫呢?

我不確定這是否是Aurelia HTTP Fetch Client的錯誤,但是添加responseError攔截器應刪除控制台中的Unhandled Exception警告。

let http = new HttpClient();

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

此錯誤也可能來自.NET Core API中的UseDeveloperExceptionPage中間件。 該中間件從響應中剝離所有標頭,這些響應會導致CORS問題,並導致您看到的“ TypeError:無法提取”錯誤。 這里是我的解決方案,這是完全描述的例子在這里

.NET核心中間件

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);
}

奧雷利亞攔截器

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);
        }); 
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM