首页 > 解决方案 > 在 ANGULAR 拦截器中捕获错误消息

问题描述

我正在尝试在 API 和客户端创建集中式错误处理程序,但角度拦截器永远不会捕获错误描述模型。拦截器中的错误消息始终是:

“url 的 Http 失败响应:0 未知错误”。

API 中的错误处理程序始终捕获每个错误和异常。当我使用 Postman 时,会定期显示错误模型。

app.UseExceptionHandler(errorApp =>
            {
                errorApp.Run(async context =>
                {
                    var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
                    var exception = errorFeature.Error;                    

                    var problemDetails = new ProblemDetails
                    {
                        Instance = $"urn:myorganization:error:{Guid.NewGuid()}"
                    };

                    if (exception is BadHttpRequestException badHttpRequestException)
                    {
                        problemDetails.Title = "Invalid request";
                        problemDetails.Status = (int)typeof(BadHttpRequestException).GetProperty("StatusCode",
                            BindingFlags.NonPublic | BindingFlags.Instance).GetValue(badHttpRequestException);
                        problemDetails.Detail = badHttpRequestException.Message;
                    }
                    else
                    {
                        problemDetails.Title = "An unexpected error occurred!";
                        problemDetails.Status = 500;
                        problemDetails.Detail = exception.Message.ToString(); 
                    }

                    // log the exception etc..

                    context.Response.StatusCode = problemDetails.Status.Value;
                    context.Response.WriteJson(problemDetails, "application/problem+json");
                });
            });

这是角度拦截器:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    return next.handle(request).pipe(
        delay(0),
        map((event: HttpEvent<any>) => {
            this.Loader = true;
                       
            return event;
        }),
        catchError((error: any) => {                
            console.log('error--->>>', error);                
            return throwError(error);
        }),
        finalize(() =>{
            this.Loader = false;
        }));
}

有人知道我做错了什么吗?

标签: c#angular.net-coreangular-http-interceptors

解决方案


推荐阅读