I'm looking for a way to handle all null reference exceptions in an asp.net application, and do an action if they are encountered, for example redirect to an error page. I have tried putting something in global.asax but it doesnt seem to work. So my question is that for example if I have a code like this that throws an exception when there is no argument:
public ActionResult GeneratePDFforSignature(int? id)
{
Signature signature = db.SignatureDatabase.Find(id);
return View();
}
How can I catch the exception application wide and stop my application from crashing. I have read up a bit on this matter and added some code to my global.asax, but it doesnt handle the null reference exceptions.
This is what I added to my Global.asax. I found it in another thread (ASP.NET MVC 5 error handling):
protected void Application_Error()
{
HttpContext httpContext = HttpContext.Current;
if (httpContext != null)
{
RequestContext requestContext = ((MvcHandler)httpContext.CurrentHandler).RequestContext;
/* when the request is ajax the system can automatically handle a mistake with a JSON response. then overwrites the default response */
if (requestContext.HttpContext.Request.IsAjaxRequest())
{
httpContext.Response.Clear();
string controllerName = requestContext.RouteData.GetRequiredString("controller");
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(requestContext, controllerName);
ControllerContext controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);
JsonResult jsonResult = new JsonResult();
jsonResult.Data = new { success = false, serverError = "500" };
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
jsonResult.ExecuteResult(controllerContext);
httpContext.Response.End();
}
else
{
httpContext.Response.Redirect(Server.MapPath("~/Shared/Error.cshtml"));
}
}
How can I catch all null reference exceptions, if it is possible? I am aware that I could fix my example code that throws this exception by adding a
if (id == null){//code}
but my program is rather large and I am hoping for a solution that will catch everything so I don't have to copy and paste a snippet of code to catch exceptions between different controllers 400 times. How can I catch all null reference exceptions and redirect to an error page in asp.net mvc 5?