Error handling in Asp.net MVC


Step 1. Add the following code in you global.asax file.

public class MyHandleErrorAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Exception != null)
        {
            //My logic

            System.Text.StringBuilder message = new System.Text.StringBuilder();

            message.Append("Hi,");
            message.AppendLine("");
            message.AppendLine("");
            message.Append("System Exception: " + filterContext.Exception.Message);
            message.AppendLine("");
            message.Append("Time: " + DateTime.Now);
            MailerFunctions.SendMails("vikas.patel@yahoo.co.in", "Application error", message.ToString());
        }
    }
}

Here,
MailerFunctions.SendMails is a function that will send a mail.
By this way you can log your system error.

Step 2: Change the web.config setting

Change system.web setting for
customErrors mode=”On”

This will show you an error page of \Views\Shared\error.aspx
By default it will display an error message:
Sorry, an error occurred while processing your request.

But you can fully customize this page.

Step 3:
And finally you need to add the attribute to each controller:

namespace MyTestProject.Controllers
{
    [HandleError]
    [MyHandleError] // add this line..
    public class HomeController : Controller
    {
    }
}