Global exception handling in database in .net core
step 1 : Create global exception solution as below
step 2:Create common folder for recording parameters and create the LogEntryRequest.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GlobalException.WebApi.Common
{
public class LogEntryRequest
{
public DateTime TimeStamp { get; set; }
public string RequestId { get; set; }
public string Message { get; set; }
public string Type { get; set; }
public string Source { get; set; }
public string StackTrace { get; set; }
public string RequestPath { get; set; }
public string Action { get; set; }
}
}
Step 3:Create filter folder and create class as below,
using GlobalException.WebApi.Common;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Filters;
//using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GlobalException.WebApi.Filter
{
public class DbExceptionFiltercs:ExceptionFilterAttribute
{
private readonly IExceptionLogService _iExceptionLogService;
[Obsolete]
private readonly IHostingEnvironment _iHostingEnvironment;
[Obsolete]
public DbExceptionFiltercs(IExceptionLogService iExceptionLogService,IHostingEnvironment iHostingEnvironment)
{
_iExceptionLogService = iExceptionLogService;
_iHostingEnvironment = iHostingEnvironment;
}
public override void OnException(ExceptionContext context)
{
if (_iHostingEnvironment.IsDevelopment())
{
LogEntryRequest log = new LogEntryRequest
{
TimeStamp = DateTime.Now,
Action = context.ActionDescriptor.DisplayName,
Message = context.Exception.Message,
RequestPath = context.HttpContext.Request.Path,
Source = context.Exception.Source,
StackTrace = context.Exception.StackTrace,
Type = context.Exception.GetType().ToString()
};
_iExceptionLogService.Add(log); //using this line exception is recorded in database
}
}
}
}
Step 4: for recording the data create the interface for recording the data in database
using GlobalException.WebApi.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GlobalException
{
public interface IExceptionLogService
{
long Add(LogEntryRequest viewModel);
}
}
now create the class to implement the interface
using GlobalException.WebApi.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GlobalException
{
public class ExceptionLogService: IExceptionLogService
{
private readonly IExceptionLogRepository _iExceptionLogRepository;
public ExceptionLogService()
{
_iExceptionLogRepository = repository;
}
public long Add(LogEntryRequest viewModel)
{
_iExceptionLogRepository.Add(viewModel);
return res;
}
}
}
Step5: now set the dependency in startup file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GlobalException.WebApi.Filter;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace GlobalException
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<IExceptionLogService, ExceptionLogService>();
services.AddScoped<DbExceptionFiltercs>();// for Error Log
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
step 6:now apply the global exception in controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GlobalException.WebApi.Filter;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace GlobalException.Controllers
{
[ServiceFilter(typeof(DbExceptionFiltercs))] calling exception on controller
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
int a = 1;
int b = 0;
//int c = 0;
int c = a / b; knowingly generate exception
//var t = 1 / 0;
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
}
No comments:
Post a Comment