Search code examples
c#.net-coreasp.net-web-api-routing

.net core 3.0 app.UseExceptionHandler is not hitting break point in Error method


I am programming a .net core 3.0 web api and trying to setup global error handeling. According to the docs this should be a simple task but I cannot get it to work. My Error method I am supposed to redirect to never hits a break point I have set in it when I throw an exception. Can you please show me what I am doing wrong and how to get the break point to be hit in my Error method?

Here is my code:

// startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

    app.UseExceptionHandler("/System/Error");
    app.UseStatusCodePages();
    app.UseStatusCodePagesWithReExecute("/system/error/{0}");

}

// SystemController.Error method

public IActionResult Error(
    [Bind(Prefix = "id")] int statusCode = 0
            )
{
    // break point never hits here and I want it to
    var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
    if (exceptionFeature != null)
    {
        // Get which route the exception occurred at   
        string routeWhereExceptionOccurred = exceptionFeature.Path;
        // Get the exception that occurred   
        Exception exceptionThatOccurred = exceptionFeature.Error;
        // TODO: Do something with the exception   
        // Log it with Serilog?   
    }
        return View();
}

Solution

  • Found the problem and the solution.

    Problem: originally I would press f5 from within vs in my web api project to run in debug mode. In the url of the web browser that showed I would put the parameters for the controller method and post it to my controller. This routine caused the debugger to break at the place I threw the error and would not break at the break point I had in the global error method.

    Solution: I got this to work fine using an external testing tool like insomnia or postman to test the web API call. I pressed f5 to run the web api project in debug mode from within Visual Studio then transferred over to insomnia and posted to the controller method and it broke in the global error method at my break point. So you have to use an external client to hit your controller in order for the break point to be hit in your global error method.