0

I am attempting to write a global exception handler to log trace information. I've modified my startup.cs Configure method and purposely did not exclude it from IsDevelopment so I could confirm it worked.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseExceptionHandler(errorApp =>
        {
            errorApp.Run(async context =>
            {
                var ex = context.Features.Get<IExceptionHandlerFeature>();
                if (ex != null)
                {
                    var errorMessage = $"Error: {ex.Error.Message}";
                    _logger.LogError(errorMessage, ex);
                    await context.Response.WriteAsync(errorMessage).ConfigureAwait(false);
                }
            });
        });

    app.UseRequestTracking();

    app.UseDeveloperExceptionPage();

    app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseMvc();
}

Then from a controller, I added a throw new exception to see the handler get hit, but it does not.

    [HttpGet]
    [Route("api/{productTenantId}/picklists")]
    public Task<List<PicklistSummary>> GetPicklists([FromUri] Guid productTenantId)
    {
        throw new Exception("testing");
        return _picklistService.GetPicklists(productTenantId);
    }

Any suggestions?

Qing Guo
  • 6,041
  • 1
  • 2
  • 10
Tom
  • 1,971
  • 3
  • 22
  • 32

1 Answers1

1

Try to remove app.UseDeveloperExceptionPage();before the app.UseExceptionHandler like below:

app.UseDeveloperExceptionPage();
app.UseExceptionHandler(errorApp =>
        {
            errorApp.Run(async context =>
            {
                var ex = context.Features.Get<IExceptionHandlerFeature>();
                if (ex != null)
                {
                    var errorMessage = $"Error: {ex.Error.Message}";
                    _logger.LogError(errorMessage, ex);
                    await context.Response.WriteAsync(errorMessage).ConfigureAwait(false);
                }
            });
        });

result:

enter image description here

Qing Guo
  • 6,041
  • 1
  • 2
  • 10