I have a base controller which takes care of excption handling . so all my actions in the controller simply delegate to the action in basecontroller.
catch (Exception ex)
{
return RedirectToAction("Error", ex);
}
my base controller action is
public ActionResult Error(Exception ex)
Teh problem here is excpetion details are getting clreared in Error Action in base controller. I think these are getting cleared during redirection.
In MVC 3 and higher exceptions caused inside the MVC pipeline had be handled, and include exception data, by using an HandleErrorAttribute and Error Views.
You would register the filer like so
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
And use a view similar to the following
#model System.Web.Mvc.HandleErrorInfo
#ViewBag.Title = "Error";
<h2>An Error Has Occurred</h2>
#if (Model != null) {
<p>
#Model.Exception.GetType().Name<br />
thrown in #Model.ControllerName #Model.ActionName
</p>
}
For a more detailed introduction see these articles:
http://blog.dantup.com/2009/04/aspnet-mvc-handleerror-attribute-custom.html
http://community.codesmithtools.com/CodeSmith_Community/b/tdupont/archive/2011/03/01/error-handling-and-customerrors-and-mvc3-oh-my.aspx
Yes, that's correct, when you do a redirect you're basically sending a 302 to the browser so the data is lost.
A possible way to temporarily save the data is saving it in the tempdata:
TempData["error"] = ex;
After that you can retrieve it in the Error-method:
Exception ex = TempData["error"] as Exception;
Note: the tempdata is for short-lived data and can be especially handy in redirect-scenarios
Related
I want to override the HandleErrorAttribute with a new version called something like HandleErrorsWithLogging. Essentially, I want it to log the unhandled exception to my log file and then proceed with the typical 'Redirect to ~/Shared/Error' functionality you get with HandleError.
I am already adding HandleError to all my actions in the global.asax
Is this the best approach or is there some easier way to gain access to that unhandled exception for logging purposes? I had also though about an Ajax call on the Error view itself.
You can create a custom filter that inherits from FilterAttribute and implements IExceptionFilter. Then register it in global.asax.cs. Also you must enable custom errors handling in the web.config:
<customErrors mode="On"/>
public class HandleErrorAndLogExceptionAttribute : FilterAttribute, IExceptionFilter
{
/// <summary>
/// The method called when an exception happens
/// </summary>
/// <param name="filterContext">The exception context</param>
public void OnException(ExceptionContext filterContext)
{
if (filterContext != null && filterContext.HttpContext != null)
{
if (!filterContext.IsChildAction && (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled))
{
// Log and email the exception. This is using Log4net as logging tool
Logger.LogError("There was an error", filterContext.Exception);
string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];
HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
// Set the error view to be shown
ViewResult result = new ViewResult
{
ViewName = "Error",
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
result.ViewData["Description"] = filterContext.Controller.ViewBag.Description;
filterContext.Result = result;
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
}
Overriding the HandleError attribute is indeed one approach into handling this. There are other approaches as well. Another approach is to use ELMAH which will take care of this so that you shouldn't worry about logging. Yet another approach consists in removing any HandleError global filters from Global.asax and subscribe for the Application_Error which is more general than HandleError as it will intercept also exceptions that happen outside of the MVC pipeline. Here's an example of such handling.
I've recently added Microsoft Unity to my MVC3 project and now I'm getting this error:
The controller for path '/favicon.ico' could not be found or it does not implement IController.
I do not really have a favicon.ico so I have no idea where that's coming from. And the weirdest thing is that the view is actually being rendered and THEN this error is being thrown... I am not sure if it's something wrong with my controller factory class because I got the code from some tutorial (I'm not to IoC - this is the first time I do that). Here's the code:
public class UnityControllerFactory : DefaultControllerFactory
{
IUnityContainer container;
public UnityControllerFactory(IUnityContainer _container)
{
container = _container;
}
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
IController controller;
if(controllerType == null)
throw new HttpException(404, string.Format("The controller for path '{0}' could not be found or it does not implement IController.",
requestContext.HttpContext.Request.Path));
if(!typeof(IController).IsAssignableFrom(controllerType))
throw new ArgumentException(string.Format("Type requested is not a controller: {0}",
controllerType.Name),
"controllerType");
try
{
controller = container.Resolve(controllerType) as IController;
}
catch (Exception ex)
{
throw new InvalidOperationException(String.Format(
"Error resolving controller {0}",
controllerType.Name), ex);
}
return controller;
}
}
Any suggestions?
Thanks in advance!
This has nothing to do with your controller factory specifically, but it is something you can easily address.
If you are using a Webkit browser (Chrome specifically, Safari too- I think), a request to any website will automatically be accompanied by a request to '/favicon.ico'. The browser is attempting to find a shortcut icon to accompany your website and (for whatever reason) the default path for shortcut icons has been standardized to be '/favicon.ico'.
To avoid the error you're getting, simply define an IgnoreRoute() within the routing table of your MVC web application:
RouteTable.Routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" });
This will ensure that any request to '/favicon.ico' (or '/favicon.gif') will not be handled by MVC.
I have seen this done as well:
catch (Exception ex)
{
/*throw new InvalidOperationException(String.Format(
"Error resolving controller {0}",
controllerType.Name), ex);*/
base.GetControllerInstance(requestContext,controllerType);
}
All,
I'm learning MVC and using it for a business app (MVC 1.0).
I'm really struggling to get my head around exception handling. I've spent a lot of time on the web but not found anything along the lines of what I'm after.
We currently use a filter attribute that implements IExceptionFilter. We decorate a base controller class with this so all server side exceptions are nicely routed to an exception page that displays the error and performs logging.
I've started to use AJAX calls that return JSON data but when the server side implementation throws an error, the filter is fired but the page does not redirect to the Error page - it just stays on the page that called the AJAX method.
Is there any way to force the redirect on the server (e.g. a ASP.NET Server.Transfer or redirect?)
I've read that I must return a JSON object (wrapping the .NET Exception) and then redirect on the client, but then I can't guarantee the client will redirect... but then (although I'm probably doing something wrong) the server attempts to redirect but then gets an unauthorised exception (the base controller is secured but the Exception controller is not as it does not inherit from this)
Has anybody please got a simple example (.NET and jQuery code). I feel like I'm randomly trying things in the hope it will work
Exception Filter so far...
public class HandleExceptionAttribute : FilterAttribute, IExceptionFilter
{
#region IExceptionFilter Members
public void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled)
{
return;
}
filterContext.Controller.TempData[CommonLookup.ExceptionObject] = filterContext.Exception;
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = AjaxException(filterContext.Exception.Message, filterContext);
}
else
{
//Redirect to global handler
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = AvailableControllers.Exception, action = AvailableActions.HandleException }));
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
}
}
#endregion
private JsonResult AjaxException(string message, ExceptionContext filterContext)
{
if (string.IsNullOrEmpty(message))
{
message = "Server error"; //TODO: Replace with better message
}
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; //Needed for IIS7.0
return new JsonResult
{
Data = new { ErrorMessage = message },
ContentEncoding = Encoding.UTF8,
};
}
}
I use the OnFailure hanlder in Ajax.Beginform(). The client-side failure handler can redirect by setting window.location (among a number of other options.) This will work in 99% of modern browsers- if the browser supports AJAX it should support this.
I need to globally redirect my users if a custom error is thrown in my application. I have tried putting some logic into my global.asax file to search for my custom error and if it's thrown, perform a redirect, but my application never hits my global.asax method. It keeps giving me an error that says my exception was unhandled by user code.
here's what I have in my global.
protected void Application_Error(object sender, EventArgs e)
{
if (HttpContext.Current != null)
{
Exception ex = HttpContext.Current.Server.GetLastError();
if (ex is MyCustomException)
{
// do stuff
}
}
}
and my exception is thrown as follows:
if(false)
throw new MyCustomException("Test from here");
when I put that into a try catch from within the file throwing the exception, my Application_Error method never gets reached. Anyone have some suggestions as to how I can handle this globally (deal with my custom exception)?
thanks.
1/15/2010 edit:
Here is what is in // do stuff.
RequestContext rc = new RequestContext(filterContext.HttpContext, filterContext.RouteData);
string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { Controller = "Home", action = "Index" })).VirtualPath;
filterContext.HttpContext.Response.Redirect(url, true);
You want to create a customer filter for your controllers / actions. You'll need to inherit from FilterAttribute and IExceptionFilter.
Something like this:
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception.GetType() == typeof(MyCustomException))
{
//Do stuff
//You'll probably want to change the
//value of 'filterContext.Result'
filterContext.ExceptionHandled = true;
}
}
}
Once you've created it, you can then apply the attribute to a BaseController that all your other controllers inherit from to make it site wide functionality.
These two articles could help:
Filters in ASP.NET MVC - Phil Haack
Understanding Action Filters
I found this answer (and question) to be helpful Asp.net mvc override OnException in base controller keeps propogating to Application_Error
Im your case the thing that you're missing is that you need to add your custom filter to the FilterConfig.cs in your App_Start folder:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomExceptionFilter());
filters.Add(new HandleErrorAttribute());
}
I'm currently using log4net in my ASP.NET MVC application to log exceptions. The way I'm doing this is by having all my controllers inherit from a BaseController class. In the BaseController's OnActionExecuting event, I log any exceptions that may have occurred:
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Log any exceptions
ILog log = LogManager.GetLogger(filterContext.Controller.GetType());
if (filterContext.Exception != null)
{
log.Error("Unhandled exception: " + filterContext.Exception.Message +
". Stack trace: " + filterContext.Exception.StackTrace,
filterContext.Exception);
}
}
This works great if an unhandled exception occurred during a controller action.
As for 404 errors, I have a custom error set up in my web.config like so:
<customErrors mode="On">
<error statusCode="404" redirect="~/page-not-found"/>
</customErrors>
And in the controller action that handles the "page-not-found" url, I log the original url being requested:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult PageNotFound()
{
log.Warn("404 page not found - " + Utils.SafeString(Request.QueryString["aspxerrorpath"]));
return View();
}
And this also works.
The problem that I'm having is how to log errors that are on the .aspx pages themselves. Let's say I have a compilation error on one of the pages or some inline code that will throw an exception:
<% ThisIsNotAValidFunction(); %>
<% throw new Exception("help!"); %>
It appears that the HandleError attribute is correctly rerouting this to my Error.aspx page in the Shared folder, but it is definitely not being caught by my BaseController's OnActionExecuted method. I was thinking I could maybe put the logging code on the Error.aspx page itself, but I'm unsure of how to retrieve the error information at that level.
I would consider simplifying your web application by plugging in Elmah.
You add the Elmah assembly to your project and then configure your web.config. It will then log exceptions created at controller or page level. It can be configured to log to various different places (like SQL Server, Email etc). It also provides a web frontend, so that you can browse through the log of exceptions.
Its the first thing I add to any asp.net mvc app I create.
I still use log4net, but I tend to use it for logging debug/info, and leave all exceptions to Elmah.
You can also find more information in the question How do you log errors (Exceptions) in your ASP.NET apps?.
You can hook into the OnError event in the Global.asax.
Something like this:
/// <summary>
/// Handles the Error event of the Application control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Application_Error(object sender, EventArgs e)
{
if (Server != null)
{
Exception ex = Server.GetLastError();
if (Response.StatusCode != 404 )
{
Logging.Error("Caught in Global.asax", ex);
}
}
}
MVC3
Create Attribute that inherits from HandleErrorInfoAttribute and includes your choice of logging
public class ErrorLoggerAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
LogError(filterContext);
base.OnException(filterContext);
}
public void LogError(ExceptionContext filterContext)
{
// You could use any logging approach here
StringBuilder builder = new StringBuilder();
builder
.AppendLine("----------")
.AppendLine(DateTime.Now.ToString())
.AppendFormat("Source:\t{0}", filterContext.Exception.Source)
.AppendLine()
.AppendFormat("Target:\t{0}", filterContext.Exception.TargetSite)
.AppendLine()
.AppendFormat("Type:\t{0}", filterContext.Exception.GetType().Name)
.AppendLine()
.AppendFormat("Message:\t{0}", filterContext.Exception.Message)
.AppendLine()
.AppendFormat("Stack:\t{0}", filterContext.Exception.StackTrace)
.AppendLine();
string filePath = filterContext.HttpContext.Server.MapPath("~/App_Data/Error.log");
using(StreamWriter writer = File.AppendText(filePath))
{
writer.Write(builder.ToString());
writer.Flush();
}
}
Place attribute in Global.asax RegisterGlobalFilters
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// filters.Add(new HandleErrorAttribute());
filters.Add(new ErrorLoggerAttribute());
}
Have you thought about extending the HandleError attribute? Also, Scott has a good blog post about filter interceptors on controllers/ actions here.
The Error.aspx view is defined like this:
namespace MvcApplication1.Views.Shared
{
public partial class Error : ViewPage<HandleErrorInfo>
{
}
}
The HandleErrorInfo has three properties:
string ActionName
string ControllerName
Exception Exception
You should be able to access HandleErrorInfo and therefore the Exception within the view.
You can try to examine HttpContext.Error, but I am not sure on this.