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).
问题:
回答1:
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).
回答2:
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);
}
}
回答3:
For completeness sake, there is also the Application_Error handler in Global.asax.
回答4:
Global Error Handling
Add in web.config
<customErrors mode="On"/>
Error will be displayed on Error.cshtml which is resides in shared folder
- Change in Error.cshtml
@model System.Web.Mvc.HandleErrorInfo @{ ViewBag.Title = "Error"; } <h2> <p>Sorry, an error occurred while processing your request.</p> <p>Controller Name: @Model.ControllerName</p> <p>Action Name : @Model.ActionName</p> <p>Message: @Model.Exception.Message</p> </h2>
回答5:
in order to make this work I followed the following blog post and then make the following addition to both Web.config files (the root one and the one in the Views folder) inside the <system.web>
node:
...
<system.web>
<customErrors mode="On"/>
...
Hope it helps...