Home > Mobile >  How to add Exception handling in logger and stored in Database
How to add Exception handling in logger and stored in Database

Time:06-16

I want when exception throw the exception error show in logger

This is my Controller i add logger in this controller i only add visited page when i visited page that will show in logger the page is visited

public class CascadingController : Controller
    {
        private readonly newnewContext _context;
        private readonly ILogger<CascadingController> _logger;

        public CascadingController(newnewContext context, ILogger<CascadingController> logger)
        {
            _context = context;
            _logger = logger;
        }
        // GET: /<controller>/
        public IActionResult Index()
        {
            throw new Exception("testing");
            _logger.LogInformation("Index page visited.");
            return View();
        }

        public JsonResult Country()
        {
            _logger.LogInformation("Country Dropdown visited.");
            var cnt = _context.Country.ToList();
            return new JsonResult(cnt);
        }

        public JsonResult State(int id)
        {
            _logger.LogInformation("State Dropdown visited.");
            var st = _context.State.Where(e => e.Country.CountryId == id).ToList();
            return new JsonResult(st);
        }

        public JsonResult District(int id)
        {
            _logger.LogInformation("District Dropdown visited.");
            var dt = _context.District.Where(e => e.State.StateId == id).ToList();
            return new JsonResult(dt);
        }
        public IActionResult Error()
        {
            return View();
        }
        public IActionResult Dropdown()
        {
            return View();
        }

CodePudding user response:

You can create an ErrorController to handle Exception, Refer to this simple Demo:

public IActionResult Index()
        {

            //log if visit this page
            _logger.LogInformation("Index page visited");

            throw new Exception("This is an Exception");


           
            return View();
        }

In Program.cs(.Net 6), Configure the ExceptionHandler

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
else
{
    //configure here
    app.UseExceptionHandler("/Error");
}

ErrorController

public class ErrorController : Controller
    {
        private readonly ILogger<ErrorController> _logger;
        private readonly IHttpContextAccessor _context;
        public ErrorController(ILogger<ErrorController> logger, IHttpContextAccessor context)
        {
            _logger = logger;
            _context = context;
        }


        [Route("Error")]
        [AllowAnonymous]
        public IActionResult Error()
        {
            var exceptionDetails = _context.HttpContext.Features.Get<IExceptionHandlerPathFeature>();

            //Here you can save this log in db, I just show it in console
            _logger.LogError($"The Path {exceptionDetails.Path} throw an exception, THe error is {exceptionDetails.Error}");

            
            return View("Error");
        }
    }

When visit this page, It will log Index page visted

enter image description here

After throw an Exception, It will catch the error then log it.

enter image description here

  • Related