Error Handling in WCF Service

658 views Asked by At

With the following service method example:-

[PrincipalPermission(SecurityAction.Demand, Role="BUILTIN\\Administrator")]
public string GetTest()
{
  try
  {
    return "Hello";
  }
  catch (Exception ex)
  {
    throw ex;
  }
}

How do I get an error from the method when the caller is not in the correct Role. In design time the error breaks on the method line (i.e. public string GetTest) and does not reach the catch. At run time it is reported in my silverlight application as an unhandled error (I have try.. catch blocks there too). There doesn't seem to be a place to catch the error as it never gets into the try blocks!!

2

There are 2 answers

2
marc_s On

The check for the role is made (by the WCF runtime) before the method is actually called - not inside the method!

You need to handle this exception on the caller's side when you make this call.

If you need to check certain conditions inside your service code, don't decorate the method with an attribute, but instead use the role provider in code to check for a given condition.

1
Ladislav Mrnka On

If you want global error handler for your WCF service you can implement IErrorHandler and add it in custom behavior. Operation can't catch exceptions thrown outside of its try block.