Error handling in 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("System Exception: " + filterContext.Exception.Message);
            message.Append("Time: " + DateTime.Now);
            MailerFunctions.SendMails("", "Application error", message.ToString());

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
    [MyHandleError] // add this line..
    public class HomeController : Controller

One thought on “Error handling in MVC

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s