当前位置: 代码迷 >> Web Service >> WebService怎么向Web客户端抛出自定义错误
  详细解决方案

WebService怎么向Web客户端抛出自定义错误

热度:36   发布时间:2012-12-17 09:31:40.0
求教:WebService如何向Web客户端抛出自定义异常
我想通过WebService向客户端抛出异常,下面是我的代码,但是捕获不到,没法Alert对话框出来。
也不知道是不是不可行还是咋的,我对WebService理解也不是很透彻,希望各位帮忙看看。

WebService

public CrmService()
{
    // 工厂类模拟的客户端激活模式
    try
    {            
        string sChannel = ConfigurationManager.AppSettings["Channel"].ToString() + "RemoteObject";            
        IRemoteObjectFactory objRemoteFactory = (IRemoteObjectFactory)Activator.GetObject(typeof(IRemoteObjectFactory), sChannel);
        objRemote = objRemoteFactory.CreateInstance();
    }
    catch (Exception ex)
    {
        throw new CrmException(ex.Message);
    }
}

客户端调用

try
{
    Service = new CrmService();
}
catch (CrmException ex)
{
    this.Alert(ex.Message);//注册脚本,弹出alert
    return;
}


自定义异常类

[Serializable]
public class CrmException : Exception, ISerializable
{
    private string _message;

    public override string Message {
        get { return _message; }
    }

    //这个一定要有,在序列化时用到
    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Message", this._message);
        base.GetObjectData(info, context);
    }

    //这个一定要有,在反序列化时用到
    public CrmException(SerializationInfo si, StreamingContext context) : base(si, context)
    {
        this._message = si.GetString("Message");
    }

    public CrmException(string message)
    {
        _message = message;
    }
}

------最佳解决方案--------------------
确实无法用正常的方式捕捉,在webservice中,所有的服务端异常,都被封装在
System.Web.Services.Protocols.SoapException中了,所以
楼主可以用类似这样的代码捕获自定义的异常


catch (SoapException ex)
        {
            if (ex.Message.IndexOf("CrmException ") > -1)
                   return;
        }


虽不严谨,但似乎也没有更好的办法
------其他解决方案--------------------
引用:
确实无法用正常的方式捕捉,在webservice中,所有的服务端异常,都被封装在
System.Web.Services.Protocols.SoapException中了,所以
楼主可以用类似这样的代码捕获自定义的异常
  相关解决方案