ASP. NET Core WEBAPI Global Exception class

Source: Internet
Author: User

Through the global exception class, all errors encountered in the program are intercepted and the results are returned amicably.

1. Customizing a global exception handling class middleware

usingMicrosoft.AspNetCore.Http;usingNewtonsoft.json;usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Net;usingSystem.Threading.Tasks;usingSystem.Xml.Serialization;usingUFX. Mall.entitymodel;usingUFX. Tools;namespaceUFX. mall.webapi{ Public classExceptionhandlermiddleware {Private ReadOnlyrequestdelegate Next;  PublicExceptionhandlermiddleware (requestdelegate next) { This. Next =Next; }         Public AsyncTask Invoke (HttpContext context) {Try            {                awaitNext (context); }            Catch(Exception ex) {awaitHandleexceptionasync (context, ex); }        }        Private Static AsyncTask Handleexceptionasync (HttpContext context, Exception Exception) {if(Exception = =NULL)return; awaitWriteexceptionasync (context, exception). Configureawait (false); }        Private Static AsyncTask Writeexceptionasync (HttpContext context, Exception Exception) {//Record LogLoghelper.error (Exception. GetBaseException ().                        ToString ()); //back to Friendly tips            varResponse =context.            Response; //Status Code            if(Exception isunauthorizedaccessexception) Response. StatusCode= (int) httpstatuscode.unauthorized; Else if(Exception isException) Response. StatusCode= (int) Httpstatuscode.badrequest; Response. ContentType= Context. request.headers["Accept"]; if(Response. Contenttype.tolower () = ="Application/xml")            {                awaitResponse. WriteAsync (object2xmlstring (Resultmsg.failure (exception. GetBaseException (). Message)). Configureawait (false); }            Else{Response. ContentType="Application/json"; awaitResponse. WriteAsync (Jsonconvert.serializeobject (Resultmsg.failure (exception. GetBaseException (). Message)). Configureawait (false); }        }        /// <summary>        ///object to XML/// </summary>        /// <param name= "O" ></param>        /// <returns></returns>        Private Static stringObject2xmlstring (Objecto) {stringwriter SW=NewStringWriter (); Try{XmlSerializer Serializer=NewXmlSerializer (O.gettype ()); Serializer.            Serialize (SW, O); }            Catch            {                //Handle Exception Code            }            finally{SW.            Dispose (); }            returnSW.        ToString (); }    }}

The return value is formatted by default into a custom class resultmsg, which returns a custom entity based on its own project requirements

It is automatically converted to XML or JSON according to the format required by the client.

2, configure registration

//This method gets called by the runtime. Use this method to configure the HTTP request pipeline         Public voidConfigure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory) {Loggerf Actory. Addconsole (Configuration.getsection ("Logging"));            Loggerfactory.adddebug (); //Configure NlogLoggerfactory.addnlog (); Env. Configurenlog ("Nlog.config"); App.            Useapplicationinsightsrequesttelemetry (); App.            Useapplicationinsightsexceptiontelemetry (); //Exception Handling Middleware            app. Usemiddleware (typeof (Exceptionhandlermiddleware)); App.        Usemvc (); }

3, call off, all exceptions can be processed

ASP. NET Core WEBAPI Global Exception class

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.