I had some issues in my test project. C#, ASP .NET MVC 5, >NET Framework 4.5.1
For some reason, my exception filter cannot catch HttpException, thrown by controller. Controller code:
[HttpGet]
[HandleError(ExceptionType = typeof(HttpException), View = "Error")]
public ViewResult Test()
{
throw new HttpException(404, "Not found!");
return View();
}
Error view:
@model HandleErrorInfo
@{
ViewBag.Title = "Sorry, something went wrong!";
Layout = "~/Views/Shared/_BasicLayout.cshtml";
}
<h1>Error: @Model.Exception.Message</h1>
<h1>Status code: @Response.StatusCode</h1>
<div style="display:none;">@Model.Exception.StackTrace</div>
I've wrote a customErrors directive in my web.config and set mode attribute to "on" and defaultRedirect attribute to /Content/StaticError.html
StaticError.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<h1>ERROR</h1>
</body>
</html>
I've tried throwing several exceptions like ArgumentOutOfRange, NullReference and some others. And I got a custon Error view as a response. But hen I am throwing HttpException without changing anything in code above I get redirected to StaticError.html.
How can I throw an HttpException and get a custom error view instead of yellow screed of death or that default redicrect page?
Any help is appreciated.
HttpException
is a special exception type known to ASP.NET MVC pipeline, its purpose is to return HTTP response with specific error code, which doesn't actually mean uncontrolled server error, so default HandleErrorAttribute
does nothing on HttpException
with code other than 500.
Look here.