Show the server exception on the silverlight client
I want to add the ability to see the server exception on the client side.
If the server got some exception => 开发者_C百科i want to show some MessageBox on the client side that will show the exception message ..
How can i do it ?
First of all, you need to enable your WCF service to return detailed error information. This is OFF by default, for security reasons (you don't want to tell your attackers all the details of your system in your error messages...)
For that, you need to create a new or amend an existing service behavior with the <ServiceDebug>
behavior:
<behaviors>
<serviceBehaviors>
<behavior name="ServiceWithDetailedErrors">
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
Secondly, you need to change your <service>
tag to reference this new service behavior:
<service name="YourNamespace.YourServiceClassName"
behaviorConfiguration="ServiceWithDetailedErrors">
......
</service>
And third: you need to adapt your SL solution to look at the details of the errors you're getting back now.
And lastly: while this setting is very useful in development and testing, you should turn those error details OFF for production - see above, for security reasons.
In addition to the things Marc mentioned you will also want to switch to the HTTP Client Stack in order to avoid the dreaded generic "Not Found" error.
bool registerResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
If you are passing the errors to the client you can use a Fault Contract:
Add this attribute to your service contract:
[OperationContract]
[FaultContract(typeof(MyCustomException))]
void MyServiceMethod();
Create the class for "MyCustomException" containing exactly the information you wish to pass to the client (in this case the full details of the exception from exception.ToString()).
Then add a try/catch around the code in the implementation of your service method:
public void MyServiceMethod()
{
try
{
// Your code here
}
catch(Exception e)
{
MyCustomException exception= new MyCustomException(e.ToString());
throw new FaultException<MyCustomException>(exception);
}
}
On the client side you can put a try / catch(FaultException e) and display the details however you like.
try
{
// your call here
}
catch (FaultException<MyCustomException> faultException)
{
// general message displayed to user here
MessageBox.Show((faultException.Detail as MyCustomException).Details);
}
catch (Exception)
{
// display generic message to the user here
MessageBox.Show("There was a problem connecting to the server");
}
精彩评论