Global handler for model state errors
We are creating MVC3 applications. We are using default editors and model state validation. We need to log application errors, but we prefer to make it by some kind of a global handler. We have a handler for un开发者_Python百科handled exceptions, but we also want to log model state errors.
The question is: Where can we attach our logger to log such errors? Can we somehow override ModelState
or detect situation when model served to view has model errors?
Global filters will most likely be your best way to go. More from SO here: asp.net mvc 3 handleerror global filter always shows IIS status 500 page
Or checkout the msdn doc here: http://msdn.microsoft.com/en-us/library/gg416513(v=vs.98).aspx
Create a attribute to handle error and register it in the controller,
public class ErrorHandlerAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext exceptionContext)
{
LogManager.GetLogger("somelogger").Error(exceptionContext.Exception.Message,exceptionContext.Exception);
base.OnException(exceptionContext);
}
}
register it in the controller like this,
[EwmsErrorHandler(ExceptionType = typeof(base type of exception to handle), View = view to redirect)]
public class MyController : Controller
{
<controller code>
}
精彩评论