ASP. NET Web API exception capture

Source: Internet
Author: User

1 sending error messages to clients

throws an error message to the client using the throw new Httpresponseexception ().

Httpresponseexception contains two overloaded constructors, one of which is the constructor parameter type httpresponsemessage, which sets the status code, The error message phrase and the message body content to throw a more verbose error message to the client. The other parameter type is HttpStatusCode, which only sets the status code.

2 Custom Exception Filters

Extended Iexceptionfilter to define the exception filter. Exception filters do not catch exceptions of type httpresponseexception, and The following exceptions cannot be caught by an exception filter:

1) exception thrown by the controller constructor

2) Exception thrown by the message handler

3) Exceptions that are thrown during routing

4) Exception thrown in response to content serialization and deserialization

code example:

 Public class Customexceptionfilterattribute:exceptionfilterattribute     {        publicoverridevoid  onexception (httpactionexecutedcontext context)        {            if (context. exception!=null)            {                Loghelper.logerror (context. Exception);     }}}

3 extending Exceptionhandler and Exceptionlogger

Extended Exceptionhandler can catch most of the exceptions, including some that cannot be caught by the exception filter. However , exceptions of type httpresponseexception are not captured.

Example code:

/// <summary>    ///Custom Exception Handlers/// </summary>     Public classGlobalexceptionhandler:exceptionhandler {/// <summary>        ///Handling Exceptions/// </summary>        /// <param name= "context" ></param>        /// <param name= "CancellationToken" ></param>        /// <returns></returns>         Public OverrideTask handleasync (exceptionhandlercontext context,cancellationtoken cancellationtoken) {if(!Shouldhandle (context)) {                returnTask.fromresult (0); } context. Result=NewErrorresult {Request=context. Exceptioncontext.request, Content="Yes, you have an exception, contact your administrator."            }; returnTask.fromresult (0); }        /// <summary>        ///decide if you should handle///late extension, overriding method filters out exceptions that you don't need to handle/// </summary>        /// <param name= "context" ></param>        /// <returns></returns>         Public Override BOOLShouldhandle (Exceptionhandlercontext context) {return true; }        Private classErrorresult:ihttpactionresult { PublicHttprequestmessage Request {Get;Set; }  Public stringContent {Get;Set; }  PublicTaskExecuteasync (CancellationToken cancellationtoken) {httpresponsemessage response=Newhttpresponsemessage (Httpstatuscode.internalservererror); Response. Content=Newstringcontent (Content); Response. Requestmessage=Request; returnTask.fromresult (response); }        }    } Public classGlobalexceptionlogger:exceptionlogger { Public OverrideTask logasync (exceptionloggercontext context,cancellationtoken cancellationtoken) {if(!Shouldlog (context)) {                returnTask.fromresult (0); }            if(Context. Exception! =NULL)            {                stringmsg =Clientinfoanalysis.getclientinfo (); Loghelper.logerror (context.            Exception, MSG); }            returnTask.fromresult (0); }        /// <summary>        ///determine if an exception should be logged///later override this method to filter out exception information that does not need to be logged/// </summary>        /// <param name= "context" ></param>        /// <returns></returns>         Public Override BOOLShouldlog (Exceptionloggercontext context) {if(Context. Exception isSystem.Web.HttpException)) {return false; }            return true; }} Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {//load the log4net configuration filelogconfigloading.load (Appsettings.log4netpathforweb); //Load Web API serviceConfig. Services.replace (typeof(Iassembliesresolver),NewServiceassembliesresolver (appsettings.serviceslocation)); //Global Exception HandlingConfig. Services.replace (typeof(Iexceptionhandler),NewGlobalexceptionhandler ()); //Global Exception RecordConfig. Services.add (typeof(Iexceptionlogger),NewGlobalexceptionlogger ());}}

4 exceptions that cannot be caught by some exceptions

Problem description

for exceptions during the service load process, the exception filter cannot be passed, i.e. System.Web.Http.Filters.IExceptionFilter interface filter to capture, nor to register exceptionlogger to achieve the purpose. here's how to fix it:

 Public Static classWebapiconfig { Public Static voidRegister (httpconfiguration config) {Try{config. Services.replace (typeof(Iassembliesresolver),NewServiceassembliesresolver (syssettings.serviceslocation)); }            Catch(Exception ex) {loghelper.error (ex); }//other Code}}

which Serviceassembliesresolver is:

 Public classServiceassembliesresolver:defaultassembliesresolver {//Service plug-in path        Private stringpath;  PublicServiceassembliesresolver (stringPath):Base()        {             This. Path =path; }         Public OverrideIcollection<assembly>getassemblies () {//access to existing servicesIcollection<assembly> baseassemblies =Base.            Getassemblies (); //Initializelist<assembly> assemblies =NewList<assembly>(baseassemblies); //load each service plug-in            foreach(stringFileinchDirectory.GetFiles (Path,"*.dll"))            {                varcontrollersassembly =assembly.loadfrom (file); Assemblies.            ADD (controllersassembly); }            returnassemblies; }    }

But the above method is probably not working, the root cause in config. Services.replace (typeof (Iassembliesresolver), New Serviceassembliesresolver (syssettings.serviceslocation)); put try-catch block , if serviceassembliesresolver Does not throw an exception when instantiated, but throws an exception when the getassemblies service plug-in The storage folder is deleted, the exception cannot be logged at this time. The problem is that the getassemblies When the method is called, discover by tracking code Register All code in the execution is complete before the service is loaded solution is Serviceassembliesresolver.getassemblies

ASP. NET Web API exception capture

Related Article

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.