Go Create Custom Exception Filter in ASP.

Source: Internet
Author: User

This article transferred from: http://www.binaryintellect.net/articles/5df6e275-1148-45a1-a8b3-0ba2c7c9cea1.aspx

In my previous article I explained how errors in an ASP. NET Core Web application can be dealt with using middleware. I also mentioned that time so you can also use exception filters to handle errors. In this article I'll explain how to does just that.

in ASP. NET MVC 5 you used the [HandleError] attribute and Onexception () Controller method to deal with exceptions that AR Ise in the actions of a controller. In ASP. The process is bit different and the overall concept is still the same. As you is probable aware of, filters sit in the net Core pipeline and allow you to execute a piece of code before or After an action execution. To understand how errors can is handled in ASP. Core Let's create an exception filter called HandleException and then Try to mimic the behavior of [HandleError] of the ASP. 5.

Begin by creating a new ASP. NET Web application. Then add a class to it named Handleexceptionattribute. This class needs to inherit from Exceptionfilterattribute base class. The complete code of this class is shown below:

 using microsoft.aspnetcore.mvc;using microsoft.aspnetcore.mvc.filters;using Microsoft.aspnetcore.mvc.modelbinding;using Microsoft.aspnetcore.mvc.viewfeatures;........public Class      handleexceptionattribute:exceptionfilterattribute{public override void Onexception (Exceptioncontext context) {      var result = new ViewResult {ViewName = "Error"};      var modelmetadata = new Emptymodelmetadataprovider (); Result. ViewData = new Viewdatadictionary (modelmetadata, context.      Modelstate); Result. Viewdata.add ("HandleException", context.      Exception); Context.      result = result; Context.    Exceptionhandled = true; }            }}

The Handleexceptionattribute class overrides the Onexception () method of T he base class. The Onexception () method is called if there is a unhandled exception in an action. Inside, we create a ViewResult object that represents the custom error page. It is assumed, the view representing the custom error page is error.cshtml. Later we'll write some code to remove this hard-coding.

Then the code creates an empty object of Emptymodelmetadataprovider class. This was required because we need to initialize the ViewData of the request and add exception details in it. Then ViewData property of the ViewResult are assigned to a new Viewdatadictionary object. While creating the Viewdatadictionary the Imodelmetadataprovider object created earlier are passed to the constructor Alo Ng with the context ' s modelstate.

We would like-to-store the exception details into the ViewData so, the Error view can retrieve them and possibly disp Lay on the page. To facilitate this HandleException key was added to the ViewData. The exception being thrown can be obtained using the context ' s exception property.

Then Result property of the context is set to the ViewResult we just configured. Finally, Exceptionhandled property was set to true to indicate that the exception need not being bubbled up any further.

Now open the HomeController and decorate the Index () action with the [HandleException] attribute.

[HandleException]public iactionresult Index () {    throw new Exception ("This is some Exception!!!");    return View ();}

Also add error.cshtml in Shared folder and write the following code to it:

@{     Exception ex = viewdata["HandleException"] as Exception;} 

As can see the Error view can grab the exception details using the handleexception key stored in the ViewData. The Message and StackTrace properties of the Exception is then outputted on the page.

If you run the "application should see the" error page like this:

So far so good. Now let's add a couple of features to our [HandleException] attribute:

    • The ViewName should be customizable
    • There should is provision to handle only specific type of exceptions

Go ahead and add public properties to the Handleexceptionattribute class. These properties are shown below:

public class handleexceptionattribute:exceptionfilterattribute{Public    string ViewName {get; set;} = "Error";    Public Type Exceptiontype {get; set;} = null;    ....    ....}

The ViewName property allows your to specify a custom view name that's then used while forming the ViewResult. The Exceptiontype property holds the Type of the exception you wish to handle (say DivideByZeroException or Formatexcepti ON).

Then modify the Onexception () as shown below:

public override void Onexception (Exceptioncontext context) {  if (this. Exceptiontype! = null)  {    if (context. Exception.gettype () = = this. Exceptiontype)    {      ....      ....    }  }  else  {    ....    ....  }}

The Onexception () method now checks whether a specific exceptiontype was to be handled (non null value). If yes then it checks whether the exception being thrown matches with that type (inner if block) and accordingly Viewresu LT is configured. If no specific exceptiontype is-checked then control-directly goes in the else block. The code in both the cases is shown below:

var result = new ViewResult {ViewName = this. ViewName}; var modelmetadata = new Emptymodelmetadataprovider (); result. ViewData = new Viewdatadictionary (modelmetadata, context. modelstate); result. Viewdata.add ("HandleException", context. Exception); context. Result = Result;context. Exceptionhandled = true;

This code was quite similar to what do you wrote earlier. But this time it uses the ViewName property while forming the ViewResult.

Now open the HomeController and change the [handleexception] attribute like this:

[HandleException (ViewName = "Customerror",exceptiontype =typeof (dividebyzeroexception))]public Iactionresult Index () {    throw new Exception ("This is some Exception!!!");    return View ();}

Now the [handleexception] attribute specifies, Properties-viewname and Exceptiontype. Since Exceptiontype is set to the type of dividebyzeroexception the [handleexception] won ' t handle the error (because Ind Ex () throws a custom Exception). So, rename error.cshtml to customerror.cshtml and throw a dividebyzeroexception. This time error gets trapped as expected.

It should is noted that [handleexception] can is applied on top of the controller class itself rather than to individual Actions.

[Handleexception]public class homecontroller:controller{...}

More details about the ASP. NET Core filters can is found here.

That ' s it for now! Keep coding!!

Bipin Joshiis a software consultant, trainer, author and a Yogi have21+ yearsof experience in software development. HE conducts online courses inASP. Mvc/core, JQuery, AngularJS, and Design Patterns. He is a published author and have authored or co-authored books for Apress and Wrox Press. Having embraced Yoga A-from life he also teaches Ajapa meditation to interested individuals. To know more on him click here.

Go Create Custom Exception Filter in ASP.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.