July 25, 2011 08:15 by
Scott
With the arrival of ASP.NET MVC 3, it is very easy for us to handle errors in ASP.NET MVC.
The HandleErrorAttribute in ASP.NET MVC lets us specify how to handle an exception that is thrown by an action method. By default, when an action method with the HandleErrorAttribute throws an exception, MVC displays the Error view that is located in the ~/Views/Shared folder.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
This filter automatically applies to any action method in any controller so that you don’t have to apply HandleErrorAttribute action level or controller level.
If user makes a request for web.config file (http://yourDomain.com/web.config), and we know that MVC restricts this request and throws an exception that is uncatchable by HandleErrorAttribute because HandleErrorAttribute just handles errors that are thrown by action methods. So for above case, traditional asp.net error window will be displayed.
Here is a diagram that show how HandleErrorAttribute works?
So how to handle errors that are not thrown by any action method means that errors those are unhandled or uncaught able by HandleErrorAttribute.
It’s simple, just create a new file ‘Error.aspx’ in the root of the project and update web.config file with this code snippet:
<customErrors mode="On" redirectMode="ResponseRewrite"
defaultRedirect="Error.aspx" />
Now, whenever an error thrown by any action method, HandleErrorAttribute are asked to handle it and ~/Views/Shared/Error.aspx view will be displayed. In contrast, when an unhandled error will occur that is not thrown by any action method, this Error.aspx file will be displayed to end user.
If you want to know what unhandled error was and you want to be informed through email, it is simple, just do it:
// for Sending Error in Email
protected void Page_Load(object sender, EventArgs e)
{
string subject = "An unhandled Error Message";
string body = HttpContext.Current.Server
.GetLastError().ToString();
subject.SendErrorMessage(body);
}
public static void SendErrorLive(this string subject,
string body)
{
WebMail.From = “[email protected]”;
WebMail.Password = “password”;
WebMail.SmtpPort = 25;
WebMail.SmtpServer = “smtp.live.com”;
WebMail.UserName = “[email protected]”;
WebMail.EnableSsl = true;
WebMail.SmtpUseDefaultCredentials = false;
WebMail.Send(“[email protected]”, subject, body);
}
Oh no, this technique is for Error.aspx but what for ~/Views/Shared/Error.cshtml?
By default, asp.net mvc passes HandleErrorInfo type to the Error.cshtml view. This type let us directly get error info as shown here:
@Model.Exception.Message
Or directly send email within the view:
@{Model.Exception.GetType().ToString()
.SendErrorMessage(Model.Exception.ToString());}
Now following errors are under your control:
1. Errors that are thrown by action methods [~/Views/Shared/Error.cshtml]
2. Any other kind of errors [Error.aspx]