I am trying to create custom exceptions for my mvc 3(razor) application. But its not working properly.
Following is the code I've written for custom exception class.
using System;
using System.Web.Mvc;
namespace TestApp.Helpers
{
public class CustomExceptionAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (!filterContext.ExceptionHandled && filterContext.Exception is Exception)
{
//filterContext.Result = new RedirectResult("/shared/Error.html");
filterContext.Result = new ViewResult { ViewName = "Error" };
filterContext.ExceptionHandled = true;
}
}
}
}
Below is the code in controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using TestApp.Domain;
using TestApp.Helpers;
namespace TestApp.Controllers
{
[CustomException]
public class MyController : Controller
{
private TestAppEntities db = new TestAppEntities();
public ActionResult Create(int id)
{
// Throwing exception intentionally
int a = 1;
int b = 0;
int c = a / b;
//This is another method which is working fine.
return View(CreateData(id, null));
}
}
}
And below is the code in 'Error.cshtml'
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = "Error";
}
<h2>
Sorry, an error occurred while processing your request.
</h2>
<div>
<p>
There was a <b>@Model.Exception.GetType().Name</b> while rendering <b>@Model.ControllerName</b>'s
<b>@Model.ActionName</b> action.
</p>
<p>
The exception message is: <b><@Model.Exception.Message></b>
</p>
<p>Stack trace:</p>
<pre>@Model.Exception.StackTrace</pre>
</div>
When we run the application it throws the error at @Model.Exception.GetType().Name, because model is null. This is the exact error: NullReferenceException: Object reference not set to an instance of an object.
Can anybody please let me know what can be the exact reason for the error? How can I fix this?
You have to pass the HandleErrorInfo
instance to the view.
string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];
HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult
{
ViewName = "Error",
ViewData = new ViewDataDictionary<HandleErrorInfo>(model)
};