在Middleware中获得例外

时间:2017-11-11 10:11:35

标签: asp.net-core exception-handling asp.net-core-middleware

我想创建一个AspNetCore中间件(旧的IHttpModule),它应该捕获异常(稍后保存它们或类似的东西)

但是,我不知道如何捕获Middleware中的Exception,尽管HttpStatusCode是500

这就是我所拥有的:

// Middleware
internal class ExceptionMiddleware
{
    private readonly RequestDelegate _next;

    public ExceptionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next.Invoke(context);
        }
        catch (Exception ex)
        {
            // never gets here
        }

        // 500
        HttpStatusCode statusCode = (HttpStatusCode)context.Response.StatusCode;

        // how to get error message?
    }
}

// Middleware Extension method
public static class ExceptionMiddlewareExtensions
{
    public static IApplicationBuilder UseExceptionMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<ExceptionMiddleware>();
    }
}

// Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseExceptionMiddleware();

    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

我触发了这样的异常:

public IActionResult Index()
{
    var test = 0;
    var a = 100 / test;

    return View();
}

2 个答案:

答案 0 :(得分:5)

您在中间件中正确使用app.UseExceptionHandler

但问题是您还注册了ExceptionHandler middlewareapp.UseExceptionHandler("/Home/Error"); app.UseExceptionMiddleware(); )。该中间件捕获所有未处理的异常,并设置500状态代码,如果可以处理它。

作为一种可能的解决方案,考虑交换中间件的顺序,因此您的中间件将是第一个捕获管道中进一步发生的异常的中间件:

private String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";
WebView webView=(WebView)findViewById(R.id.webView);
webView.loadurl(url);

答案 1 :(得分:2)

你重新发明了轮子。

如果没有自己的中间件,该怎么做:

您可以使用内置的ExceptionHandlerMiddlewareapp.UseExceptionHandler)获取错误详细信息ASP.NET Core为您提供,但未记录,但它应该是。

When exception occurs this middleware sets IExceptionHandlerFeature (with exception that occured) and IExceptionHandlerPathFeature (with derives from IExceptionHandlerFeature) on HttpContext.

因此,您可以通过HttpContext.Features

访问您的例外详细信息

假设您在/Home/Error控制器的操作中调用此功能,您可以访问它:

var exHandlerFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
var exception = exHandlerFeature.Error;

Also see this answer and question about Request Features