none
关于c#应用程序的异常.

    问题

  • 有个中间件程序是检查应答状态是否为500,如果状态是500的话,则返回抛出的异常。

    Startup.cs

    ...
    
     app.UseMiddleware<APIExceptionMiddleware>();
    
    app.UseMvc();
    
    ...

    APIExceptionMiddleware.cs:

    public class APIExceptionMiddleware
        {
            private readonly RequestDelegate _next;
            public APIExceptionMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task Invoke(HttpContext context)
            {
                context.Response.OnStarting(
                    callback: (state) =>
                    {  
                        HttpResponse response = (HttpResponse)state;
                        if (response.StatusCode == 500)
                        {
                            // want to grab exception here turn it into JSON response place it in the response.Body but not sure how I access the exception.
                            return response.WriteAsync("An Error Occured");
                        }
                        return Task.FromResult<object>(null);
                   }, state: context.Response);
                await _next.Invoke(context);
            }
        }

    例如请求到达 UseMvc() 我抛一个异常,我可以用app. UseDeveloperException()我想使用JSON API来做应答,如果返回状态是500的话,则抛异常,问题是:中间件怎么才能得到这个异常呢?

    2016年2月22日 12:23

答案

  • 你好,

    看一下developerexceptionpagemiddleware的代码(链接如下),特别是invoke这段(代码如下),  一旦有500的异常,返回一段JSON就可以了。

    https://github.com/aspnet/Diagnostics/blob/4e5c99fabc6afdc67a181fad2b7d20ec59ab4225/src/Microsoft.AspNetCore.Diagnostics/DeveloperExceptionPage/DeveloperExceptionPageMiddleware.cs

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            _logger.LogError(0, ex, "An unhandled exception has occurred while executing the request");
    
            if (context.Response.HasStarted)
            {
                _logger.LogWarning("The response has already started, the error page middleware will not be executed.");
                throw;
            }
    
            try
            {
                context.Response.Clear();
                context.Response.StatusCode = 500;
    
                await DisplayException(context, ex);
    
                if (_diagnosticSource.IsEnabled("Microsoft.AspNetCore.Diagnostics.UnhandledException"))
                {
                    _diagnosticSource.Write("Microsoft.AspNetCore.Diagnostics.UnhandledException", new { httpContext = context, exception = ex });
                }
    
                return;
            }
            catch (Exception ex2)
            {
                // If there's a Exception while generating the error page, re-throw the original exception.
                _logger.LogError(0, ex2, "An exception was thrown attempting to display the error page.");
            }
            throw;
        }
    }

    Best regards,

    Cole Wu

    2016年2月23日 12:44
    版主