I'm pretty new to MVC. Below is the code that I have added to an existing MVC 5 application. The code is using log4net to log any run-time error/exception.
NOTE: I could override OnException()
in MVC filter "HandleErrorAttribute" but I preferred to have this functionality in my custom Controller
base class.
Can anyone please review and provide feedback?
BaseController.cs
public class BaseController: Controller
{
private log4net.ILog logger;
protected override void OnException(ExceptionContext filterContext)
{
//Log error
logger = log4net.LogManager.GetLogger(filterContext.Controller.ToString());
logger.Error(filterContext.Exception.Message, filterContext.Exception);
//If the request is AJAX return JSON else redirect user to Error view.
if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
//Return JSON
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { error = true, message = "Sorry, an error occurred while processing your request." }
};
}
else
{
//Redirect user to error page
filterContext.ExceptionHandled = true;
filterContext.Result = this.RedirectToAction("Index", "Error");
}
base.OnException(filterContext);
}
}
HomeController.cs
public class HomeController : BaseController
{
...
}
Global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
private static readonly ILog log = LogManager.GetLogger(typeof(MvcApplication));
protected void Application_Error(object sender, EventArgs e)
{
//Log exception
Exception exception = Server.GetLastError();
log.Error(exception);
//Clear error from response stream
Response.Clear();
Server.ClearError();
//Redirect user
Context.Server.TransferRequest("~/Error/");
}
...
}
For displaying errors, I have a basic ErrorController.cs with just Index()
Action along with its associated Error/Index.cshtml.
Some blogs suggests different error pages for different type of errors (such as 404 error). Do I need to handle them separately?
Please share if you have any ideas to improve upon my code in terms of usability and logging details.