Как обработать WebFaultException, чтобы вернуть CustomException?

Я создал собственное исключение, которое будет вызываться внутри 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 у меня нет проблем с созданием собственного исключения. А вот в REST я столкнулся с массой трудностей.

Вот метод создания исключения 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 вернет это на стороне клиента:

enter image description here

Но, в конце концов, она всегда вернет это:

enter image description here

Что мне делать? Пожалуйста помоги.

РЕДАКТИРОВАТЬ

Вот пример ответа при вызове службы мыла:

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

Видели ли вы «InvalidLogin»? Это то, что я хочу видеть в ответе службы REST.
Пример ответа от REST:

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

Я выбрасываю WebFaultException, но получаю WebException.
Если я не смогу получить точное сообщение об ошибке в REST, я выберу SOAP.
Спасибо за ответы.

7
задан tereško 19 May 2013 в 08:25
поделиться