如何处理Wcf Rest服务中的异常

时间:2014-04-30 07:35:08

标签: c# wcf rest exception-handling dotnet-httpclient

我有一个方法,它需要一些参数,响应是json格式。 成功时,它将返回int类型值。 但是如果发生错误,那么rest服务将抛出异常,因为实现REST服务的方法必须返回int值。

    internal static int AddCatalog(string name, Guid key, string userName)
    {
        using (var client = new HttpClient())
        {
            HttpResponseMessage response = client.PutAsync(AdminRestServiceUrl + "xml/updatecatalog?cid=" + null + "&name=" + name + "&key=" + key + "&uby=" + userName, null).Result;
            response.EnsureSuccessStatusCode();
            var cid= response.Content.ReadAsStringAsync().Result;
            return Convert.ToInt32(cid);
        }
    }

如果服务引发错误,我该怎样才能有效地处理它? 如果我喜欢这个

if(response.IsSuccessStatusCode == HttpStatusCode.OK)
{
return convert.ToInt32(cid);
}
else
{
return ?? //how to handle error here as method must retun int type
}

请建议我如何将详细的错误消息传递给客户端,以便通知他们服务中发生的确切错误。 非常感谢任何形式的帮助/建议。

1 个答案:

答案 0 :(得分:1)

你可以做一个" ErrorLogs"上课,保持"状态"其中的字段,以及"消息"中的错误异常字段,如果发生任何错误发送状态失败

在两种情况下都返回一个具有错误日志和整数值的类,如果有错误返回整数为-1并在客户端上处理它

相关问题