Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core - Use both UseDeveloperExceptionPage() and custom logging

I have the following code in my ASP.NET Core application to handle errors:

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler(builder =>
            {
                builder.Run(async context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    var loggingService = context.RequestServices.GetService<ILoggingService>();
                    var exceptionFeature = context.Features.Get<IExceptionHandlerFeature>();
                    if (exceptionFeature != null)
                    {
                        Exception ex = exceptionFeature.Error;
                        Console.Error.WriteLine(ex.Message + "   " + ex.StackTrace);
                        loggingService.Error(ex);
                    }
                });
        }

However, when being in a Development environment, I would like to use both the UseDeveloperExceptionPage() and the custom error handling for DB logging. But it seems that this does not work (the UseExceptionHandler() disables the functionality of UseDeveloperExceptionPage()).

Is there any way to achieve this, without writing the UseDeveloperExceptionPage() code form scratch?

like image 436
user2173353 Avatar asked Apr 05 '19 10:04

user2173353


1 Answers

For built-in UseDeveloperExceptionPage, it did not expose any extension method to custom the error process, you could try implement your own middleware to log the error like

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
};
app.Use(async (context, next) =>
{
    try
    {
        await next.Invoke();
    }
    catch (Exception ex)
    {
        //var loggingService = context.RequestServices.GetService<ILoggingService>();
        //loggingService.Error(ex);
        Console.Error.WriteLine(ex.Message + " My " + ex.StackTrace);
        throw;
    }

});
like image 157
Edward Avatar answered Oct 20 '22 14:10

Edward