C#:web Service Exception Handling

Source: Internet
Author: User
Tags definition constructor count exception handling reference regular expression visual studio
Web| exception handling when a Web service is implemented in. NET, any user exceptions (exceptions other than SoapException) that are generated in the Web service interface are packaged as SoapException passed to the client, making it difficult to handle the web in the usual way The service exception. This article describes how to implement consistent exception handling through Soapexceptionhelper.

Exception handling problems for WEB service
When a Web service is implemented in. NET, any user exceptions (exceptions other than SoapException) that are generated in the Web service interface are packaged as SoapException passed to the client. The user error information is placed in the SoapException message property.

The following example shows the user exception information for a SoapException package. WebMethod Interface TestException code throws a InvalidOperationException:

[WebMethod]
public void TestException () {
throw new InvalidOperationException ("Invalid Operation.");
}

The WebMethod client will catch a SoapException exception, message messages as follows:



Where message messages contain a section of "...-->[1]:[2] at ...", [1] is a user exception class, [2] is a user exception message. and an original SoapException (with the new SoapException (...) The way the exception is created and thrown, the following is an original SoapException message:



Unfortunately, the current SoapException does not provide more direct means to directly obtain the original exception information, the only user exception information contained in the message string, for the use of Web service as a distributed mechanism of the application system is very inconvenient, The caller cannot catch the original exception, and it is difficult to get user-friendly exception information. At the same time, because the Web Service interface agent no longer throws the original exception, the application developers need to consider two completely different exception handling mechanisms, resulting in the complexity of the program structure.

Create SoapException helper class: Soapexceptionhelper
The Soapexceptionhelper helper class contains the following main interfaces:

Isuserexception: Whether it is a userexception
Userexception: Return to the original userexception
Message: Error messages for the original exception.
Get the original user exception class and exception message
With the regular expression class, we can get the original user exception class and the exception message:

<summary>
Read userexception information.
</summary>
private void Readuserexceptioninfo () {
Match user Exception class
System.Text.RegularExpressions.MatchCollection MC =
Regex.Matches (Soapexception.message, "---> ([^:]+):");
if (MC. Count >= 1) {
Userexceptionclass = mc[0]. GROUPS[1]. Value;
Match User Exception message
MC = regex.matches (Soapexception.message, "---> [^:]+:(. *)");
if (MC. Count > 0) userexceptionmessage = mc[0]. GROUPS[1]. Value;
}
}

Create a user exception instance
The Userexception interface uses the reflection mechanism to create an original exception class instance:

... ...
Assembly callingassemply = assembly.getcallingassembly ();
Type exceptiontype = Getexceptiontype (callingassemply); Get user Exception type definition
Exception e = null;
try {
try {
E = Activator.CreateInstance (Exceptiontype, new object[]{userexceptionmessage}, NULL) as Exception;
}
Catch {}
If no exists constructor with message parameter, use no parameters constructor.
if (E = = null) E = Activator.CreateInstance (exceptiontype) as Exception;
}catch (Exception ex) {
throw new Soapexceptionhelperexception (Userexceptionclass, ex);
}

return e;

Create a problem with a user exception
Because a user exception may be defined in a different integration block, Soapexceptionhelper may not know its location, and cannot get the exception type correctly, such as an integration block with Soapexceptionhelper and a call integration block ( callingassembly) is no longer the exception class in the same reference scope. Soapexceptionhelper If you cannot create an instance of the original exception, you create a System.Exception object instance.

In order to create the true original exception class, the caller can obtain the actual exception type externally and pass it to Soapexceptionhelper, because the caller can explicitly refer to the integration block where the exception definition resides. Examples are as follows:

The integration block where the exception definition is introduced in the project reference
...
Soapexceptionhelper helper = new Soapexceptionhelper (SE);
Type type = Type.GetType (helper. Userexceptionclass, "< the integration block where the exception class is located >");
Exception e = helper. Getuserexception (type);

If the exception type definition is not passed externally, Soapexceptionhelper attempts to get the exception type definition in the following order:

Executing Assembly
Calling Assembly
Referenced assemblies (of calling Assembly)
System.Exception
Using Soapexceptionhelper
Returns a user-friendly message
Use Soapexceptionhelper to display the error message in Example 1:

try {
...//Call Web method
catch (SoapException se) {
MessageBox.Show (New Soapexceptionhelper (SE). message); Show "Invalid Operation." String
}
 

Shielding SoapException
The Web service client proxy class can then throw back the original exception after capturing SoapException, which can effectively mask the differences in Web service exception handling and allow the application to handle exceptions in a consistent local manner. The following code modifies the Web Service Client Proxy Class (Reference.cs file) generated by Visual Studio to implement this mechanism (the bold part is the new code):

[System.Web.Services.Protocols.SoapDocumentMethodAttribute ("Http://tempuri.org/TestException", Requestnamespace = "http://tempuri.org/", responsenamespace= "http://tempuri.org/", use= System.Web.Services.Description.SoapBindingUse.Literal, parameterstyle= System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void TestException () {
try{
This. Invoke ("TestException", new object[0]);
}catch (SoapException se) {
Soapexceptionhelper helper = new Soapexceptionhelper (SE);
if (helper. isuserexception) throw helper. Userexception; Rethrow User exception
else throw;
}
}



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.