In this article, I will be explaining 3 different ways to handle exceptions and display a friendly error page to the end user. Friendly Error Pages are the pages that you design to show the end user when any kind of not handled exception happens in your application and your expected result is not achieved. So, instead of presenting your end user with technical information regarding the exception, you show him a friend page. Also, presenting your end user with technical information is not a security best practice.
So, let's see the three ways.
Method 1: Custom Exception Filter
Custom Exception Filter
It is a filter that is called every time an exception occurs in the applied methods.
Why would I use a custom exception filter?
Because with a custom exception filter, you can handle in a generic way every kind of exception thrown by your actions and/or controllers. You may use custom exception filters to log your exceptions.
Steps to achieve this:
Step 1
Create a new class named CustomExceptionFilter.
What this custom exception does is to redirect to your About action in your Home Controller. Do not forget to set the ExceptionHandled equal to true; otherwise it will not take effect.
Step 2
Step 1
Create a new class named CustomExceptionFilter.
- public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
- {
- public void OnException( ExceptionContext filterContext )
- {
- filterContext.Result = new RedirectResult( "Home/About" );
- filterContext.ExceptionHandled = true;
- }
- }
Step 2
Apply your custom exception filter to your controller/action.
- public class HomeController : Controller
- {
- [CustomExceptionFilter]
- public ActionResult Index()
- {
- throw new Exception();
- return View();
- }
- public ActionResult About()
- {
- ViewBag.Message = "Your application thrown an exception";
- return View();
- }
- public ActionResult Contact()
- {
- ViewBag.Message = "Your contact page.";
- throw new Exception();
- return View();
- }
- }

C# CornerPosted Apr 15, 2018, 9:33 AM
Very nice explanation and implementing the exception handling by different ways.
Goutham KsPosted Apr 13, 2018, 2:46 AM
Very nice explanation..Vivas