In the previous tutorial, I introduced the development of the filter in the Web API, which left a pit when it comes to Exceptionfilter: Exceptionfilter can only intercept and handle exceptions that occur during action execution. If an exception occurs outside of the action execution process, Exceptionfilter is powerless.
These exceptions include:
1, the controller constructs the exception that appears in the method
2. Anomalies appearing in Messagehandlers
3. Exceptions that occur during routing
4, the body in the serialization/deserialization process occurred in the exception
As you can see, exceptionfilter only resolves the exception that occurred during the Apicontroler successfully instantiated and executed, and in order to solve this problem, in addition to Exceptionfilter in the Web API, we introduced two exception records, Extension points for processing:
Iexceptionlogger and Iexceptionhandler.
The two extensions are registered and managed as pipeline components of the Web API, and they have different divisions:
Iexceptionlogger, as the exception logging component, is responsible for logging after an exception, which runs through the entire Web API's lifecycle, and in the Web API framework, any one of the request cycles is not captured/ The exception that is handled will first go into the Exception Log record pipeline, which can register multiple Iexceptionlogger instances for different exception handling in the Web API.
Iexceptionhandler, as an exception handling component, is responsible for the processing of the exception, which is at the very end of the exception handling pipeline, when the Iexceptionlogger component is logged and no related exceptoinfilter is handled for exception handling. will eventually call Exceptionhandler for exception handling, in the Web API, with only one exceptionhandler for exception handling.
Two base classes are given in the Web API framework: Exceptionlogger and Exceptionhandler, when using the Exceptionlogger base class, he provides a shouldlog virtual method that is called in the base class. The effect is to prevent the same exception from being duplicated by the same Exceptionlogger instance (for example, when the exception is thrown in subsequent pipelines, Or the same Exceptionlogger object is accidentally registered two times will be duplicated record possible) we can also replicate the Shouldlog method to add our own anomaly record judgment logic to make different Exceptionlogger calls for different scenarios. If interested can decompile the Exceptionlogger base class look, he used the display interface implementation, a very interesting technique. Let's take a look at an example of Exceptionlogger use:
public class Errologger:exceptionlogger { public async Task Logasync (exceptionloggercontext context, CancellationToken CancellationToken) { var sb = new StringBuilder (); Get the Log component ILogger log = Logmanager.getcurrentclasslogger (); var request = context. Request; Sb. Appendline ("URL:"); Get URL var url = Request. Requesturi.tostring (); Sb. Appendline (URL); Log. Error (context. EXCEPTION,SB. ToString (), ""); } public override bool Shouldlog (Exceptionloggercontext context) { return context. Exception is Demoexception && base. Shouldlog (context); } }
In this example, we rewrite the shouldlog to ensure that this exceptionlogger only records demoexception of this type of exception, and also calls the base class method, guaranteeing that the same exception will not be recorded repeatedly. In the Logasync method, I logged the request URL that caused the exception through the log component, and the exception information was logged.
Next we are going to register this component:
Write in the Register method in the App_start/webapiconfig.cs file
Config. Services.add (typeof (Iexceptionlogger), New Errologger ());
In this way, an exception logging component for Demoexception is completed and registered, and a component is logged when an unhandled demoexception exception occurs in the Web API execution pipeline.
Next we write a exceptionhandler, in the entire Web API framework, Exceptionhandler can only provide an instance, as with Exceptionlogger, We can inherit the Exceptionhandler base class to simplify exception handling, and the Shouldhandle method is provided in Exceptionhandler to determine whether the exception should be handled and to avoid repeating exceptions that are repeatedly thrown by other parts of the pipeline. We also provide an example:
public class Errorhandler:exceptionhandler {public override async Task Handleasync (exceptionhandlercontext Context, CancellationToken CancellationToken) { if (context. Exception is demoexception) { context. Result = new Responsemessageresult (context. Request.createresponse (Httpstatuscode.badrequest,new {message=context. Exception.Message})); } else { context. Result = new Responsemessageresult (context. Request.createresponse (httpstatuscode.internalservererror,new {Message = "server has been kidnapped by Aliens"})
In this example, we determine the type of the exception and return the client's different response content and different HTTP status codes based on different exceptions.
The exception handling module is then registered in the configuration and written in the Register method in the App_start/webapiconfig.cs file
Config. Services.replace (typeof (Iexceptionhandler), New ErrorHandler ());
This replaces the system default Exceptionhandler, which can be handled with our custom handler.
In the exception record, processing, we all encounter the corresponding exception context parameters, we can get the context of the current request through this parameter, get the request, response (caution is sometimes empty OH), capture the exception of the Catch block information, etc., we can use this information to better describe, record, handle the exception.
The simple development of exceptionlogger components and Exceptionhandler components is done here. In the development process, we can see that Exceptionlogger is responsible for the global exception record, in the Web API framework pipeline under the unhandled exception Exceptionlogger will be captured, recorded. While the Exceptionhandler and exceptionfilter functions overlap, when is the use of Exceptionhandler when using Exceptionfilter? We can make a list of the differences between the two as follows:
|
Exceptionfilter |
Exceptionhandler |
Scope |
Controller , Action |
Global |
Number of instances |
Unlimited |
Globally unique |
function conditions |
Controller after the instantiation succeeds |
Web API after successful loading |
Through the table above we can see that if the processing granularity to the controller, the action level, Exceptionfilter processing will be more handy, he has been able to pinpoint an action, and then can be customized for the current action development. The Exceptionhandler scope is much larger than Exceptionfilter, and he has the advantage of dealing with the global.
About Web API exception handling what I'm saying is that if there are any incorrect places or questions in the article, you are welcome to point it out for me.