首页 > 解决方案 > Angular:无法通过 HttpResponse 返回自定义错误消息

问题描述

当我们在控制器操作中返回错误文本作为ActionResult/JsonResult或使用HttpRequest如下方法时,我一直在谷歌搜索解决方法并查看示例

HttpContext.Current.Response.Status = "error text";

对于我使用的后端应用程序ASP.NET Core 2.1.1,课程.Status中缺少属性HttpResponse

此外,我找不到任何可能包含我的自定义错误消息的属性。

我使用中间件类来获取异常描述并将其传递为JSON

Startup.cs

app.UseMiddleware<ExceptionHandleMiddleware>();

班级本身

public class ExceptionHandleMiddleware
{
    private readonly RequestDelegate next;

    public ExceptionHandleMiddleware(RequestDelegate next)
    {
        this.next = next ?? throw new ArgumentNullException(nameof(next));
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            context.Response.Clear();
            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = StatusCodes.Status500InternalServerError;

            await context.Response.WriteAsync(JsonConvert.SerializeObject(new { error = $"{ex.GetType().FullName}: '{ex.Message}'" }));
        }
    }
}

看看线

context.Response.StatusCode = StatusCodes.Status500InternalServerError;

这是必需的,因为在我使用的Angular 6 应用程序HttpInterceptor中,为了捕获错误,您应该返回 HTTP 错误(否则.catch(...)不会在 Angular 拦截器中触发该块)。

这是我的 Angular 应用程序中的一点

@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {

    constructor(
        private notify: NgNotify,
    ) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next
            .handle(req)
            .catch(this.handleError)
    }
    ...

尽管context.Response.WriteAsync(...)bit确实返回了异常文本,但我无法在.catch(...)拦截器块中提取它。

public handleError = (error: Response) => {

这里error打印为(请注意,它缺少“Last Entry”JSON的错误消息)

{  
    "headers":{  
       "normalizedNames":{  

       },
       "lazyUpdate":null
    },
    "status":500,
    "statusText":"OK",
    "url":"https://localhost:44305/api/Entry/GetNext?id=11962",
    "ok":false,
    "name":"HttpErrorResponse",
    "message":"Http failure response for https://localhost:44305/api/Entry/GetNext?id=11962: 500 OK",
    "error":{  

    }
 }

不过,如果我打开 chrome 的网络选项卡,我可以看到以下内容

在此处输入图像描述

所以,我似乎无法从error: Response.

也许,有人知道将错误传递给 Angular 客户端并在那里获取它的更好方法?

更新 1 - 错误处理程序(我只是将断点放在那里以调查错误的内容)

public handleError = (error: Response) => {
    debugger
    return Observable.throw(error)
}

标签: c#angularasp.net-coreangular-http-interceptorsasp.net-core-middleware

解决方案


我的疏忽。

如果您查看返回的 JSON

  ....

  "message":"Http failure response for https://localhost:44305/api/Entry/GetNext?id=11962: 500 OK",
  "error":{  

  }
}

error似乎是一个空对象

事实上errorBlob我们应该按照以下方式阅读

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next
        .handle(req)
        .catch(this.handleError)
}

public handleError = (error: Response) => {

    let reader = new FileReader();

    let ngNotify = this._ngNotify;

    reader.onload = function () {

        var result = JSON.parse(this.result);

        ngNotify.nofity('Error', result.error);
    };

    reader.readAsText(error['error']);

    return Observable.throw(error)
}

就是这样。


推荐阅读