2012-05-03 36 views
5

Từ hiểu biết của tôi sau nên ném đúng một lỗi tùy chỉnh từ một dịch vụ WCF giải trí:WCF Rest xử lý lỗi dịch vụ & WebChannelFactory

[DataContract(Namespace = "")] 
public class ErrorHandler 
{ 
    [DataMember] 
    public int errorCode { get; set; } 

    [DataMember] 
    public string errorMessage { get; set; } 
} // End of ErrorHandler 

public class Implementation : ISomeInterface 
{ 
    public string SomeMethod() 
    { 
     throw new WebFaultException<ErrorHandler>(new ErrorHandler() 
     { 
      errorCode = 5, 
      errorMessage = "Something failed" 
     }, System.Net.HttpStatusCode.BadRequest); 
    } 
} 

Trong Fiddler này dường như làm việc, tôi nhận được các dữ liệu thô sau:

HTTP/1.1 400 Bad Request 
Cache-Control: private 
Content-Length: 145 
Content-Type: application/xml; charset=utf-8 
Server: Microsoft-IIS/7.5 
X-AspNet-Version: 4.0.30319 
Set-Cookie: ASP.NET_SessionId=gwsy212sbjfxdfzslgyrmli1; path=/; HttpOnly 
X-Powered-By: ASP.NET 
Date: Thu, 03 May 2012 17:49:14 GMT 

<ErrorHandler xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><errorCode>5</errorCode><errorMessage>Something failed</errorMessage></ErrorHandler> 

Nhưng bây giờ đứng về phía khách hàng của tôi tôi có đoạn mã sau:

WebChannelFactory<ISomeInterface> client = new WebChannelFactory<ISomeInterface>(new Uri(targetHost)); 

ISomeInterface someInterface = client.CreateChannel(); 
try 
{ 
    var result = someInterface.SomeMethod(); 
} 
catch(Exception ex) 
{ 
    // Try to examine the ErrorHandler to get additional details. 
} 

Bây giờ khi mã chạy, nó chạm vào bắt và là một System.ServiceModel.ProtocolException với thông báo 'Máy chủ từ xa trả về một phản ứng không mong muốn: (400) Yêu cầu không hợp lệ.'. Có vẻ như tôi không có cách nào để xem chi tiết ErrorHandler tại thời điểm này. Có ai chạy vào điều này? Có cách nào tôi có thể nhận được các chi tiết ErrorHander vào thời điểm này?

Trả lời

4

WebChannelFactory hoặc ChannelFactory sẽ chỉ tiết lộ cho bạn số chung CommunicationException. Bạn sẽ cần phải sử dụng hành vi IClientMessageInspector hoặc dựa trên WebRequest để trả lại lỗi thực tế.

Cách tiếp cận IClientMessageInspector - xem nhận xét trong this blog entry.

Cách tiếp cận WebRequest, bạn có thể thực hiện theo các bước sau để bắt số WebException.

try { } 
catch (Exception ex) 
{ 
    if (ex.GetType().IsAssignableFrom(typeof(WebException))) 
    { 
     WebException webEx = ex as WebException; 
     if (webEx.Status == WebExceptionStatus.ProtocolError) 
     { 
      using (StreamReader exResponseReader = new StreamReader(webEx.Response.GetResponseStream())) 
      { 
       string exceptionMessage = exResponseReader.ReadToEnd(); 
       Trace.TraceInformation("Internal Error: {0}", exceptionMessage); 
      } 
     } 
    } 
} 
Các vấn đề liên quan