Reputation: 170479
In my MVC3 application I have lots of controllers and actions. Sometimes an exception is raised while executing an action. I want to be able to log that and let the exception be handled by MVC.
Something like this pseudocode:
try {
MvcInvokeControllerAction( controller, action, params );
} catch( Exception e ) {
trace( "Error while invoking " + controller + "-" +
action + " with " + params + " details: " + getDetails( e ) );
throw;
}
What I want is to be able to catch the exception before it is first processed by MVC because sometimes MVC kicking in raises another exception and I see the latter in Application_Error()
and the original exception is lots.
How do I achieve such hooking?
Upvotes: 1
Views: 170
Reputation: 3061
You can override OnException Method On your Basecontrollor.
This will be a Catch block for all exceptions in Controllor Actions. just Exetnd all your Controllors from Basecontrollor
protected override void OnException(ExceptionContext filterContext)
{
}
Example
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);
// Handle error here
}
}
public class TestController : BaseController
{
public ActionResult Index()
{
// If any exceptions then will be caught by
// BaseController OnException method
}
}
Upvotes: 1