The first two articles mainly introduce the error transfer between WCF and the client. In actual projects, we need to catch exceptions for every operation in the service contract, we usually record the files through logs,
When there are many operations, log processing is added for each method.ProgramIt is inconvenient. in ASP. NET, you can write it in application_error. In WCF, ierrorhandler class implementation is provided.
The ierrorhandler interface is defined as follows and mainly provides two methods. For details, see msdn
NamespaceSystem. servicemodel. Dispatcher
{
Public InterfaceIerrorhandler
{
VoidProvidefault (Exception error, messageversion version,RefMessage fault );
BoolHandleerror (Exception error );
}
}
The handleerror method ensures the execution of Error-related behaviors, including error logging, fast fault reporting, and application closure. This article uses this interface to process logs.
1. Define the class implementing ierrorhandler
Public ClassErrorhandler: ierrorhandler
{
Public BoolHandleerror (system. Exception error)
{
Return True;
}
Public VoidProvidefault (system. Exception error, messageversion version,RefMessage fault)
{
// Log processing
Streamwriter =NewStreamwriter (@ "D: \ log.txt");
Streamwriter. Write (error. Message );
Streamwriter. Close ();
}
}
Define the log processing logic in providefault. This sectionCodeOnly for demonstration.
2. Add the errorhandler to the applydispatchbehavior of the defined silverlightfaultendpointbehavior.
Endpointdispatcher. channeldispatcher. errorhandlers. Add (NewErrorhandler ());
After a simple step, we implement global processing of the WCF logs. According to the above Code logic, we can see the recorded error information in D: \ log.txt.
The next article describes how to configure the WCF error message in code mode.
Download Code: wcfexceptionlesson2.rar