简体   繁体   中英

How to throw FaultException from self hosting wcf service?

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.

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.

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM