I want to handle uncaught exceptions in my ASP.NET MVC 3 application, so that I may communicate the error to the user via the application's error view. How do I intercept uncaught exceptions? I'd like to be able to do this globally, not for each controller (although I wouldn't mind knowing how to do this as well).
Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally, and throw. try − A try block identifies a block of code for which particular exceptions is activated.
The specific procedure is as follows. When an uncaught exception occurs, the JVM does the following: it calls a special private method, dispatchUncaughtException(), on the Thread class in which the exception occurs; it then terminates the thread in which the exception occurred1.
Exception class. An exception is thrown from an area of code where a problem has occurred. The exception is passed up the call stack to a place where the application provides code to handle the exception. If the application does not handle the exception, the browser is forced to display the error details.
You can set up a global error filter in Global.asax
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
The above sets up a default error handler which directs all exceptions to the standard error View. The error view is typed to a System.Web.Mvc.HandleErrorInfo
model object which exposes the exception details.
You also need to turn on custom errors in the web.config to see this on your local machine.
<customErrors mode="On"/>
You can also define multiple filters for specific error types:
filters.Add(new HandleErrorAttribute
{
ExceptionType = typeof(SqlException),
View = "DatabaseError",
Order = 1
});
/* ...other error type handlers here */
filters.Add(new HandleErrorAttribute()); // default handler
Note that HandleErrorAttribute
will only handle errors that happen inside of the MVC pipeline (i.e. 500 errors).
you can use HandleErrorAttribute filters,
[ErrorHandler(ExceptionType = typeof(Exception), View = "UnhandledError", Order = 1)]
public abstract class BaseController : Controller
{
}
basically you can have this on top of a base controller and define the UnhandledError.cshtml in the Shared views folder.
And if you want to log the unhandled errors before you show the error message then you can extend the HandleErrorAttribute class and put the logic to do the logging inside the OnException method.
public class MyErrorHandlerAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext exceptionContext)
{
Logger.Error(exceptionContext.Exception.Message,exceptionContext.Exception);
base.OnException(exceptionContext);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With