Reputation: 1566
I try to handle 404 and 500 error in ASP.NET MVC 6.
I have Action in controller which render page with error status and description:
[HttpGet]
[Route("/Errors/{status}")]
public IActionResult Errors(int status)
{
var model = Mapper.Map<ErrorViewModel>(BaseData);
model.ErrorCode = status;
if (error_descriptions.ContainsKey(status))
model.Description = error_descriptions[status];
else
model.Description = "Неизвестная ошибка";
return View(model);
}
I enable status code pages and exception handler:
app.UseExceptionHandler("/Errors/500"); app.UseStatusCodePagesWithReExecute("/Errors/{0}");
I want to ger 404
error when url doesn't match any route and when queryes to Database return empty sequencies (access to nonexists elements).
I've got InvalidOperationException
when LINQ return empty sequence (the sequence contains no elements
). I want to handle global exception, show 404
in this case and 500
in other.
I make a simple filter and check Exception in OnException
:
public void OnException(ExceptionContext context)
{
logger.LogError(context.Exception.Message);
if (context.Exception is System.InvalidOperationException) ;
//NEED TO CALL HomeController.Error(404)
}
It works, but I don't know how to call my action and show error page
Upvotes: 3
Views: 3078
Reputation: 77926
You can create a model in the OnException
method like
public void OnException(ExceptionContext context)
{
var model = new HandleErrorInfo(filterContext.Exception, "YourError Controller","Errors");
}
Upvotes: 1