Monday, 27 October 2014

6 Ways To Handle The Exceptions In Asp.Net MVC 4

Handling exceptions and presenting them to the user in appropriate way instead of default error message is best approach to tell end user "What to do when it happen?"

I found several ways to handle errors but I'm posting the popular ones.

1. Redirect to Custom Error - Simplest Approach

In try..catch block, if you want to redirect to custom error page on the basis of specific conditions you can use HandleErrorInfo class to do so. Example is

// Define variable of type Exception & HandleErrorInfo Exception exception; HandleErrorInfo errorInfo; // Do something like you filter the Client with Id // And clientPresent is a variable which hold Client data which // is use futher to insert its Customers if (clientPresent != null) { // Add its Customer } else { exception = new Exception("Unable to recognize the Client!"); errorInfo = new HandleErrorInfo(exception, "Home", "Index"); return View("Error", errorInfo); }

In above code, you define the appropriate message, add it to HandleErrorInfo class. HandleErrorInfo class contains three parameters.
  • Exception           : Custom format of message
  • Controller Name  : Where this exception raise
  • Action Name       : Action name contains exception

2. Writing try..catch

A classic approach to catch any exception. You use this inside the controller code and handle the exceptions that may occur. Here the only thing you have to take into account is what is the controller action is returning. Here you have two approaches & choose one to follow. First approach is "If you return a view, when you catch an exception you should redirect to an error page." is define above and second approach is "when you return JSON you should return a JSON with the exception message and handle it on the client side" is define here:

public ActionResult Index() { try { //Do stuff here } catch (Exception e) { //Redirect to an error page Response.Redirect("URL to the errror page"); } return View(); } public JsonResult GetJson() { try { } catch (Exception e) { //Return the exception message as JSON return Json(new { error = e.Message }); } return Json("Return data here"); }

The main disadvantage of this approach is that you have to use it everywhere and you bloat the code.

3. Override OnException method inside the Controller

You can handle all the exceptions inside a controller is by overriding the OnExeception method. With this approach you code only one exception handling routine per

Controller and you don`t bloat the code. Example is:

protected override void OnException(ExceptionContext filterContext) { //If the exeption is already handled we do nothing if (filterContext.ExceptionHandled) { return; } else { //Determine the return type of the action string actionName = filterContext.RouteData.Values["action"].ToString(); Type controllerType = filterContext.Controller.GetType(); var method = controllerType.GetMethod(actionName); var returnType = method.ReturnType; //If the action that generated the exception returns JSON if (returnType.Equals(typeof(JsonResult))) { filterContext.Result = new JsonResult() { Data = "Return data here" }; } //If the action that generated the exception returns a view if (returnType.Equals(typeof(ActionResult)) || (returnType).IsSubclassOf(typeof(ActionResult))) { filterContext.Result = new ViewResult() { ViewName = "URL to the errror page" }; } } //Make sure that we mark the exception as handled filterContext.ExceptionHandled = true; }

But same disadvantage that you have to override the OnExecption method inside every controller it`s not the best approach. You need to react in a different way if your exception throwing action returns a view or returns JSON. Also, you have to make sure that you specify that the exception was handled. Skipping this will throw the exception further.

4. Using the HandleError attribute

You can use HandleError attribute. When you provide this attribute to your controller class or to your action method, when an unhandled exception is encountered MVC will look first for a corresponding view named Error in the controller`s view folder. If it can`t find it there, it will look inside the shared view folder and redirect to that view.

[HandleError] public ActionResult Index() { return View(); }

You can also filter the type of error you want to handle

[HandleError(ExceptionType = typeof(SqlException))] public ActionResult Index() { return View(); }

5. Extending the HandleError attribute

You can code your own logic to handle errors using attributes. All you have to do is to extend the existing HandleErrorAttribute and override the OnException method. All you need to create a custom HandleErrorAttribute using the logic mentioned above.

public class HandleCustomError : System.Web.Mvc.HandleErrorAttribute { public override void OnException(System.Web.Mvc.ExceptionContext filterContext) { //If the exeption is already handled we do nothing if (filterContext.ExceptionHandled) { return; } else { //Determine the return type of the action string actionName = filterContext.RouteData.Values["action"].ToString(); Type controllerType = filterContext.Controller.GetType() ; var method = controllerType.GetMethod(actionName); var returnType = method.ReturnType; //If the action that generated the exception returns JSON if (returnType.Equals(typeof(JsonResult))) { filterContext.Result = new JsonResult() { Data = "Return data here" }; } //If the action that generated the exception returns a view //Thank you Sumesh for the comment if (returnType.Equals(typeof(ActionResult)) || (returnType).IsSubclassOf(typeof(ActionResult))) { filterContext.Result = new ViewResult { ViewName = "URL to the errror page" }; } } //Make sure that we mark the exception as handled filterContext.ExceptionHandled = true; } }

You use this custom implementation like this

[HandleCustomError] public ActionResult Index() { return View(); }

6. Handle all errors inside Global.asax

This method uses a global error handling that captures all exceptions into a single point. The only problem is to determine if we have to return a view or some JSON in case of AJAX request. Included in the snippet below there is a method that uses reflection to do all this.

public class MvcApplication : System.Web.HttpApplication { void Application_Error(object sender, EventArgs e) { //We clear the response Response.Clear(); //We check if we have an AJAX request and return JSON in this case if (IsAjaxRequest()) { Response.Write("Your JSON here"); } else { //We don`t have an AJAX request, redirect to an error page Response.Redirect("Your error page URL here"); } //We clear the error Server.ClearError(); } //This method checks if we have an AJAX request or not private bool IsAjaxRequest() { //The easy way bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest") || ((Request.Headers != null) && (Request.Headers["X-Requested-With"] == "XMLHttpRequest")); //If we are not sure that we have an AJAX request or that we have to return JSON //we fall back to Reflection if (!isAjaxRequest) { try { //The controller and action string controllerName = Request.RequestContext. RouteData.Values["controller"].ToString(); string actionName = Request.RequestContext. RouteData.Values["action"].ToString(); //We create a controller instance DefaultControllerFactory controllerFactory = new DefaultControllerFactory(); Controller controller = controllerFactory.CreateController( Request.RequestContext, controllerName) as Controller; //We get the controller actions ReflectedControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType()); ActionDescriptor[] controllerActions = controllerDescriptor.GetCanonicalActions(); //We search for our action foreach (ReflectedActionDescriptor actionDescriptor in controllerActions) { if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper())) { //If the action returns JsonResult then we have an AJAX request if (actionDescriptor.MethodInfo.ReturnType .Equals(typeof(JsonResult))) return true; } } } catch { } } return isAjaxRequest; } //snip }

Getting Started - ASP MVC



What ASP.NET MVC is and how to install it, and use tutorials to get started.
  1. Get Started with ASP.NET MVC and Azure

    A short tutorial that creates a simple ASP.NET application and deploys it to Azure.
  2. Getting Started with ASP.NET MVC 5 (11 Tutorials)

    Introduction to ASP.NET MVC 5
  3. Introduction to ASP.NET MVC

    New to ASP.NET MVC? This free 8 hour course for absolute beginners starts with the basics and slowly builds up to more advanced concepts like view customization with Bootstrap and how to configure authentication. All slides and demo source code are provided.
  4. Pluralsight ASP.NET MVC 5 Fundamentals (video course)

    Pluralsight ASP.NET MVC 5 Fundamentals
  5. Getting Started with EF 6 using MVC 5 (12 Tutorials)

    The basics of using Entity Framework 6 to display and edit data in an ASP.NET MVC 5 application.
  6. EF Database First with ASP.NET MVC (7 Tutorials)

    This series shows how to use Database First development for creating an MVC 5 application with Entity Framework
  7. Deploy a Secure ASP.NET MVC 5 app with Membership, OAuth, and SQL Database to a Windows Azure Web Site

    How to build a secure ASP.NET MVC 5 web application that enables users to log in with credentials from Facebook and Google. Also shows how to deploy the application to Windows Azure.
  8. ASP.NET MVC Facebook Birthday App

    By Kirthi Krishnamraju, Rick Anderson, Yao Huang Lin, Troy Dai and Tom Dykstra|
    This tutorial will teach you how to build a Facebook app by using an MVC 5 NuGet package and Visual Studio 2013.
  9. Get Started with ASP.NET MVC and Azure WebJobs

    Build, run, and deploy a simple multi-tier application that runs in Azure Websites, using Azure WebJobs for background processing and the Azure WebJobs SDK for working with Azure storage queues and blobs.
  10. Get Started with ASP.NET MVC and Azure Cloud Services

    Build, run, and deploy a simple multi-tier application that runs in an Azure Cloud Service web role and worker role.
  11. ASP.NET MVC Multi-Tier Application Using Azure Service Bus Queues

    In this tutorial, you'll build and run a multi-tier application in an Azure Cloud Service.
  12. Lifecycle of an ASP.NET MVC 5 Application

    By Cephas Lin|
    Download a PDF document that charts the lifecycle of an ASP.NET MVC 5 application. This lifecycle document provides a high-level view of the MVC lifecycle and a detailed view that shows all the ext...
  13. Monitoring and Telemetry

    Links to resources about monitoring the health and performance of an ASP.NET application.
  14. MVC Recommended Resources

    By Rick Anderson|
    Links to documentation resources about ASP.NET MVC.

Getting Started With ASP.NET Web API - Tutorials, Videos, Samples


ASP.NET team shipped the beta version of ASP.NET Web API which has been known as WCF Web API for more than a year. It has seen 6 preview versions and we have now nearly the final bits and pieces. The beta version of the product has been merged with ASP.NET MVC so that we won’t feel ourselves in a fork in the road in order to create REST APIs.
In my opinion, ASP.NET Web API is really exciting because it offers a simple and pluggable way to expose your data to the World. The one of the best parts is that you don’t have to just expose it as XML or JSON. You have the XML and JSON support out of the box but the format of the data is really up to you. Since nearly all of the devices out there today know how to communicate through HTTP, your data has the best possible reach.
One of the other great features of ASP.NET Web API is that everything has been built asynchrony in mind. So, you can scale out very easily. On the other hand, don’t act prejudicial that it is ASP.NET based and cannot run anywhere other than IIS. It has a self hosting capability as well (I honestly don’t know how it works at the background but it looks promising).
It has been not much since the product beta version has shipped but there are pretty good blog posts and articles about ASP.NET Web API out there. Instead of writing one, I would like to point you those resources.

Note

The follwing set of blog posts have been wtitten based on the beta release of ASP.NET Web API. It is highly likely that there will be some sort of conflicts if you are playing with a later version of the product.
Getting Started
Routing
Validation, Data Annotations & Model Binding
    Message Handlers, Filters & Formatters
    HttpClient
    Dependency Injection & Unit Testing
    Self Hosting
    Uncategorized
    Samples
    Also, there are some great videos done by @jongalloway on ASP.NET web site as well as some other videos:
    ASP.NET Web API Video Series
    ASP.NET Web API Videos of Mine On NedirTv (In Turkish)
    Some Other Great Talks, Webcasts and Other Type of Visuals

    After-Beta Resources

    The following blog posts target the features and changes which will be available for the next release of the product after beta.
    Some Other Great Talks, Webcasts and Other Type of Visuals
    If you have any other related blog post, tutorial, sample or whatever related to ASP.NET Web API, please comment and I will add them to this list. I will also add new things to this list that I come across. Enjoy:)

    Angular Tutorial (Update to Angular 7)

    As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...