如何处理WebFaultException返回CustomException?(How to Han

2019-06-24 21:48发布

我提出,将try-catch代码里面每一个错误发生时被抛出我的自定义异常:

[Serializable]
public class CustomException : Exception
{
    public CustomException() { }

    public CustomException(string message)
        : base(message) { }

    public CustomException(string message, Exception innerException)
        : base(message, innerException) { }
}  

我有两个服务,REST和SOAP。 对于SOAP服务,我没有就扔我的自定义异常任何问题。 但在休息时,我遇到了很多困难。

下面是抛出WebFaultException的方法:

    public static WebFaultException RestGetFault(ServiceFaultTypes fault)
    {
        ServiceFault serviceFault = new ServiceFault();
        serviceFault.Code = (int)fault;
        serviceFault.Description = ConfigAndResourceComponent.GetResourceString(fault.ToString());
        FaultCode faultCode = new FaultCode(fault.ToString());
        FaultReasonText faultReasonText = new FaultReasonText(serviceFault.Description);
        FaultReason faultReason = new FaultReason(faultReasonText);
        WebFaultException<ServiceFault> webfaultException = new WebFaultException<ServiceFault>(serviceFault, HttpStatusCode.InternalServerError);

        throw webfaultException;
    }  

ServiceFault是一类在那里有我用它来把我需要的所有信息的一些属性。

我用这个方法抛出REST服务中的异常:

    public static CustomException GetFault(ServiceFaultTypes fault)
    {
        string message = fault.ToString();
        CustomException cusExcp = new CustomException(message, new Exception(message));
        throw cusExcp;
    }  

样品REST服务(登录方法):

    [WebInvoke(UriTemplate = "Login", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    public Session Login(ClientCredentials client, LogCredentials loginfo)
    {
        try
        {
            // Login process
            return copied;
        }
        catch (LogicClass.CustomException ex)
        {
            LogicClass.RestGetFault(LogicClass.EnumComponent.GetServiceFaultTypes(ex.Message));
            throw ex;
        }
    }  

MVC的部分:

控制器:

    [HttpPost]
    public ActionResult Login(LoginCredentials loginfo)
    {
        try
        {
            string param = "{\"client\":" + JSonHelper.Serialize<ClientAuthentication>(new ClientAuthentication() { SessionID = Singleton.ClientSessionID })
                           + ", \"loginfo\":" + JSonHelper.Serialize<LoginCredentials>(loginfo) + "}";

            string jsonresult = ServiceCaller.Invoke(Utility.ConstructRestURL("Authenticate/Login"), param, "POST", "application/json");
            UserSessionDTO response = JSonHelper.Deserialize<UserSessionDTO>(jsonresult);

        }
        catch (Exception ex)
        {
            return Json(new
            {
                status = ex.Message,
                url = string.Empty
            });
        }

        return Json(new
        {
            status = "AUTHENTICATED",
            url = string.IsNullOrWhiteSpace(loginfo.r) ? Url.Action("Index", "Home") : loginfo.r
        });
    }  

我用ServiceCaller.Invoke调用REST API和检索响应:ServiceCaller.cs

public class ServiceCaller
{
    public static string Invoke(string url, string parameters, string method, string contentType)
    {
        string results = string.Empty;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
        request.Method = method;
        request.ContentType = contentType;

        if (!string.IsNullOrEmpty(parameters))
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
            request.ContentLength = byteArray.Length;
            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();
        }

        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (HttpStatusCode.OK == response.StatusCode)
            {
                Stream responseStream = response.GetResponseStream();
                int length = (int)response.ContentLength;

                const int bufSizeMax = 65536;
                const int bufSizeMin = 8192;
                int bufSize = bufSizeMin;

                if (length > bufSize) bufSize = length > bufSizeMax ? bufSizeMax : length;

                byte[] buf = new byte[bufSize];
                StringBuilder sb = new StringBuilder(bufSize);

                while ((length = responseStream.Read(buf, 0, buf.Length)) != 0)
                    sb.Append(Encoding.UTF8.GetString(buf, 0, length));

                results = sb.ToString();
            }
            else
            {
                results = "Failed Response : " + response.StatusCode;
            }
        }
        catch (Exception exception)
        {
            throw exception;
        }

        return results;
    }
}  

我期待的REST服务,在客户端返回此:

但最终,它总是返回此:

我该怎么办? 请帮忙。

编辑

这里是调用SOAP服务时的示例响应:

[FaultException: InvalidLogin]
   System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9441823  

你有没有看到“InvalidLogin”? 这就是我想看到从REST servivce的响应。
从REST示例响应:

[WebException: The remote server returned an error: (500) Internal Server Error.]
   System.Net.HttpWebRequest.GetResponse() +6115971  

我抛出一个WebFaultException但是我收到一个WebException
如果我将无法获取对REST确切的错误信息,我会去SOAP。
感谢您的答案。

Answer 1:

当使用HttpWebRequest (或JavaScript客户端),您的自定义异常对他们没有意义。 只是HTTP错误代码(如500内部服务器错误 ),并在响应中的内容的数据。

所以,你必须自己处理异常。 例如,如果赶上WebException你可以阅读根据您的服务器配置的XML或JSON格式的内容(错误消息)。

catch (WebException ex)
{
    var error = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
    //Parse your error string & do something
}


Answer 2:

我只是有类似的问题,几分钟回来。 也许它帮助。 我试图用像下面我所有的服务电话分机:

这里是BAD一段代码:

public static void ExecuteServiceMethod(this IMyRESTService svc, Action svcMethod)
{ 
    try
    {
       // try to get first last error here
       string lastError = svc.CommHandler.CH_TryGetLastError();
       if (!String.IsNullOrEmpty(lastError))
          throw new WebFaultException<string>(lastError, System.Net.HttpStatusCode.InternalServerError);

       // execute service method
       svcMethod();
    }
    catch (CommHandlerException ex)
    {
       // we use for now only 'InternalServerError'
       if (ex.InnerException != null)
           throw new WebFaultException<string>(ex.InnerException.Message, System.Net.HttpStatusCode.InternalServerError);
       else
           throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
     catch (Exception ex)
     {
        throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
}

下面是固定片的代码:

public static void ExecuteServiceMethod(this IMyRESTService svc, Action svcMethod)
{
    // try to get first last error here
    string lastError = svc.CommHandler.CH_TryGetLastError();
    if (!String.IsNullOrEmpty(lastError))
       throw new WebFaultException<string>(lastError, System.Net.HttpStatusCode.InternalServerError);

    try
    {
       // execute service method
       svcMethod();
    }
    catch (CommHandlerException ex)
    {
       // we use for now only 'InternalServerError'
       if (ex.InnerException != null)
           throw new WebFaultException<string>(ex.InnerException.Message, System.Net.HttpStatusCode.InternalServerError);
       else
           throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
     catch (Exception ex)
     {
        throw new WebFaultException<string>(ex.Message, System.Net.HttpStatusCode.InternalServerError);
     }
}

所以......也许你注意到了第一个throw ,被处理成catch (Exception ex)再次抛出,使其始终显示块:“内部服务器错误 ”。 也许有帮助,因为我看你也有一个全球性的

赶上(例外的例外){抛出异常; }

这可能是它的原因。



Answer 3:

1)faultcontract添加到方法/操作

2)抛出WebFaultException或WebFaultException

3)在客户端侧掣成引发WebException然后读取异常响应

catch (WebException exception)
{
var resp = new StreamReader(exception.Response.GetResponseStream()).ReadToEnd();
}

面对同样的问题,在这个问题发言中提到,并能够通过LB提到的答案来解决,跟着其他几个职位。 所以总结遵循的步骤



文章来源: How to Handle WebFaultException to return CustomException?