如何从自托管wcf服务抛出FaultException

本文关键字:服务 FaultException wcf | 更新日期: 2023-09-27 17:49:39

我计划在windows服务中托管服务,但我正在考虑标题中描述的问题。有人有类似的问题吗?由于

更新

问题是当你在WinForms/WPF/Win Service应用程序中抛出一个异常时,程序会崩溃,你必须重新启动它。

如何从自托管wcf服务抛出FaultException

异常并不总是使您的服务器崩溃。即使是意外的服务器端异常也会被转移到客户端。但它被认为比预期的更严重,破坏了通道。

基本思想是在接口契约中包含预期的异常(错误)。有很多方法可以做到这一点,这里有一篇介绍文章。

当然,你还需要在服务器端处理良好的异常。

你可以尝试的一件事是通过挂接主机应用程序的Main方法入口点中的threadexeption事件来拦截任何异常,以检查它是否是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
    }
}