public static void EncapsulateExceptions(this IApplicationBuilder app, string product, string layer, string defMessage) { app.UseExceptionHandler(eApp => { eApp.Run(async context => { context.Response.StatusCode = 500; context.Response.ContentType = "application/json"; IWebLogger logger = (IWebLogger)context.RequestServices.GetService(typeof(IWebLogger)); var errorCtx = context.Features.Get <IExceptionHandlerFeature>(); if (errorCtx != null) { var ex = errorCtx.Error; logger.LogException(product, layer, null, ex, null, context); var errorId = Activity.Current?.Id ?? context.TraceIdentifier; var jsonResponse = JsonConvert.SerializeObject(new CustomErrorResponse { ErrorId = errorId, Message = defMessage }); await context.Response.WriteAsync(jsonResponse, Encoding.UTF8); } }); }); }