How to throw FaultException from self hosting wcf service?

泪湿孤枕 提交于 2019-12-25 03:19:23

问题


I'm planning to host the service in windows service, but I'm thinking about the problem described in the title. Anyone had similar issue? Thanks

Update

The problem is that when you throw an exception in WinForms/WPF/Win Service app, the program crashes and you'll have to restart it.


回答1:


An exception does not always crash your server. Even an unexpected server-side exception will be transferred to the client. It is considered more severe than an expected one though, faulting the channel.

The basic idea is to include the expected exceptions (faults) in you interface contracts . There are many ways to do that, here is an introduction article.

And of course you need decent exception handling at the server.




回答2:


A thing you can try is to intercept any exceptions by hooking to the ThreadException event in the Main method entry point of your Host application to check whether it is a FaultException.

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());

        // Hook to this event below
        Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
    }

    static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
        if (e.Exception is FaultException)
            return; // Bypass FaultExceptions;
        else
            throw e.Exception; // Throw otherwise
    }
}


来源:https://stackoverflow.com/questions/5606937/how-to-throw-faultexception-from-self-hosting-wcf-service

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