【问题标题】:Get the exception that was thrown earlier in application c#?获取之前在应用程序 c# 中引发的异常?
【发布时间】:2016-02-12 07:14:16
【问题描述】:

我在回调中编写了一些中间件,用于检查响应是否为 500。如果是 500,我想返回抛出的异常。如何获取应用程序中引发的异常?

Startup.cs

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

// Add MVC to the request pipeline.
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();并获得一个带有堆栈跟踪和异常的友好的 HTML 页面。

我几乎想重复一遍,但要让它成为我的应用程序的友好的 JSON api 响应。因此,如果抛出 500,我将使用中间件将其转换为漂亮的 json 响应,并通过 api 请求将其作为我的响应发送出去。我的问题是如何在中间件中获取这个异常?

如果 UseDeveloperException() 正在做,我不应该也能做到吗?

【问题讨论】:

  • 没有上下文。错误
  • 你的意思是没有暴露的属性或者它是空的?
  • 没有上下文错误属性。
  • Server.GetLastError() 是否在范围内?
  • 不确定不是,因为这是红隼

标签: c# asp.net asp.net-core


【解决方案1】:

查看DeveloperExceptionPageMiddleware 的代码...尤其是Invoke(HttpContext context)(如下所示)。不要使用您当前添加的默认中间件,而是使用您自己的已启动的中间件。这将非常类似于DeveloperExceptionPageMiddleware:捕获任何异常,但不是返回错误页面,而是根据需要格式化您的 JSON 响应。

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

【讨论】:

  • 这正是我想要的。
  • 请记住,泄露有关您的系统的信息是一种安全风险
  • 是的,我有一些我想通过的不是所有的。我会用一个决定来通过那些我想要忽略其他的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-12-22
  • 1970-01-01
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
相关资源
最近更新 更多