Catching custom exception from WCF

匆匆过客 提交于 2019-12-25 06:47:19

问题


I have a Custom class, InvalidCodeException in Project A

public class InvalidCodeException : Exception
    {
        public InvalidCodeException ()
        {
        }
        public InvalidCodeException (string message)
            : base(message)
        {            
        }

        public InvalidCodeException (string message, Exception innerException)
            : base(message, innerException)
        {

        }
    }

a WCF service in Project B. And a client in Project C. Project A is referenced in Project B and C.

I am throwing InvalidCodeException from Project B and catching in Project C. Problem is that when debuggin, the exception is not catching in

catch (InvalidCodeException ex)
{
  Trace.WriteLine("CustomException");
  throw;
}

but in

catch (Exception ex)
{ throw; }

回答1:


WCF will not serialize exceptions automatically, for many reasons(e.g. client may be written in some other language than C#, and run on platform that is different from .NET).

However, WCF will serialize some exception information into FaultException objects. This basic information contains exception class name, for example. You may store some additional data inside them if you use generic FaultException type. I.e. FaultException<FaultInfo> where FaultInfo is your class that stores additional exception data. Don't forget to add data contract serialization attributes onto class properties.

Also, you should apply FaultContract attributes on methods that are supposed to throw FaultExceptions of your kind.

[OperationContract]
[FaultContract(typeof(FaultInfo))]
void DoSomething();



回答2:


That's because all exceptions are wrapped in FaultException. Catch it and look at the InnerException property

MSDN Article




回答3:


The correct way to handle this is to define a FaultContract on your service operation contract:

[OperationContract]
[FaultContract(typeof(MyException))]
int MyOperation1(int x, int y);

This will allow your client to handle the exception by catching it as a generic FaultException:

try {...}
catch (FaultException<MyException> e) {...}


来源:https://stackoverflow.com/questions/18331183/catching-custom-exception-from-wcf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!