ViewComponent exception handling
Hi,
What is the correct way to handle exceptions in a view component? I would like the user to end up being redirected to an error page.
My ViewComponent looks like this :
public async Task<IViewComponentResult> InvokeAsync()
{
StandingsViewModel model = new StandingsViewModel();
try
{
//model populated here
return View(model);
}
catch
{
//redirect to error screen, pass parameter
_httpContextAccessor.HttpContext.Response.Redirect("/Home/Error/VC123");
return View(new StandingsViewModel());
}
}
And the action in the controller where the view component is used is in this format :
public IActionResult Index()
{
try
{
HomeIndexModel model = new HomeIndexModel();
//model populated here
return View(model);
}
catch (Exception ex)
{
IPAddress ip = Helpers.Extensions.GetIPAddress(Request.Headers,
Request.HttpContext.Connection.RemoteIpAddress);
ErrorLog el = new ErrorLog
{
Controller = ControllerContext.ActionDescriptor.ControllerName,
Action = ControllerContext.ActionDescriptor.ActionName,
IPAddress = ip.ToString(),
ErrorDateTimeUtc = DateTime.UtcNow,
ExceptionType = ex.GetType().Name,
ErrorMessage = ex.Message,
StackTrace = ex.StackTrace,
UserId = (User != null) ? _userManager.GetUserId(User) : null
};
_ctx.ErrorLogs.Attach(el);
_ctx.ErrorLogs.Add(el);
_ctx.SaveChanges();
//redirect to error screen, pass parameter
return RedirectToAction("Error", "Home", new { id = "HM097" });
}
}
Is this the right way to do this? Should I catch exceptions in the view component and redirect from there, or is it possible to do it in the view that is using the view component and if so how?
Thanks in advance!