2013-04-18 2 views
9

내 서비스 클라이언트가 모두 WebServiceException을 처리하려고합니다. 지금 당장 할 수있는 좋은 방법이 있습니까?ServiceClientBase의 예외 처리기

예를 들어 Windows Forms 앱 주위에 단일 ServiceClientBase를 전달합니다. api 키를 http 헤더의 서버에 전달하고 있습니다. api 키가 유효하지 않은 요청에 대해 사용자에게 요청이 승인되지 않았 음을 알리는 메시지 상자를 표시하고 API 키를 설정해야합니다.

이 같은
try 
{ 
    _client.Get(new ReqDto()); 
} 
catch (WebServiceException ex) 
{ 
    if(ex.StatusCode == 401) 
     Util.ShowUnauthorizedMessageBox(); 
} 

뭔가 좋은 것 : :하지만 사방이 코드 싶지 않아 난에 연결할 수 로컬 응답 필터가 알고

_client.WebServiceExceptionHandler += TheHandler; 

을,하지만 난 구체화 된 WebServiceException 필요 .

저는 ServiceClientBase.cs를보고 무엇을 할 수 있는지 알고 싶지만 어떤 도움을 주시면 감사하겠습니다. 감사.

답변

2

API 질문이 아닌 디자인 질문으로 접근 할 수 있다면 대답은 서비스 클라이언트를 래핑하는 것입니다. 개인적으로, 클라이언트에서 서비스 예외를 기록 할 수 있도록 비슷한 작업을 수행했습니다. 시간이 지남에

public class MyServiceClient : IDisposable 
{ 
    public ServiceClientBase ServiceClient { get; set; } 

    string _serviceUri; 
    public string ServiceUri 
    { 
     get { return _serviceUri; } 
     set { _serviceUri = value; ServiceUriChanged(); } 
    } 

    public MyServiceClient() 
    { 
     ServiceUri = "http://127.0.0.1:8080"; 
    } 

    public void Dispose() 
    { 
     ServiceClient.Dispose(); 
    } 

    public TResponse Get<TResponse>(IReturn<TResponse> request) 
    { 
     try 
     { 
      return ServiceClient.Get(request); 
     } 
     catch (WebServiceException ex) 
     { 
      if(ex.StatusCode == 401) 
       Util.ShowUnauthorizedMessageBox(); 
     } 
    } 

    void ServiceUriChanged() 
    { 
     if (ServiceClient != null) 
      ServiceClient.Dispose(); 
     ServiceClient = new JsonServiceClient(ServiceUri); 
    } 
} 

당신은 & 반응 [디버그 콘솔] 모든 요청을 기록, 로컬 캐싱을 추가하는 등 간접이 추가 수준의 다른 혜택을 찾을 수 있습니다 :

는 출발점이 될 수있다. 그리고 일단 모든 클라이언트 코드에서 사용되면 유지 보수 비용이 상당히 저렴합니다.

API에 관한 한, 내가 원하는 것만 제공한다고 생각하지 않습니다. 개인적으로, 나는 그대로 (특별히 IReturn<T> 인터페이스가 원하는 기능을 통합 할 때 도움이 됨) 기뻐했습니다. 하지만 만족스럽지 않다면, 개선을 위해 Demis 대화 상자에서 한 요청을 멀리합니다. (- =

1

게임에 약간 늦었지만 같은 것을 실행하고 있었기 때문에 원본을 파헤 치기 시작했습니다. 실제로이 간단한 해결 방법을 사용하면 어떤 ServiceClient에서든지 HandleResponseException 메서드를 재정의 할 수 있습니다. 사용 코멘트에서 직접 :.

 /// <summary> 
     /// Called by Send method if an exception occurs, for instance a System.Net.WebException because the server 
     /// returned an HTTP error code. Override if you want to handle specific exceptions or always want to parse the 
     /// response to a custom ErrorResponse DTO type instead of ServiceStack's ErrorResponse class. In case ex is a 
     /// <c>System.Net.WebException</c>, do not use 
     /// <c>createWebRequest</c>/<c>getResponse</c>/<c>HandleResponse&lt;TResponse&gt;</c> to parse the response 
     /// because that will result in the same exception again. Use 
     /// <c>ThrowWebServiceException&lt;YourErrorResponseType&gt;</c> to parse the response and to throw a 
     /// <c>WebServiceException</c> containing the parsed DTO. Then override Send to handle that exception. 
     /// </summary> 

을 개인적으로하여 JsonServiceClient

protected override bool HandleResponseException<TResponse>(Exception ex, object request, string requestUri, Func<System.Net.WebRequest> createWebRequest, Func<System.Net.WebRequest, System.Net.WebResponse> getResponse, out TResponse response) 
    { 
     Boolean handled; 
     response = default(TResponse); 
     try 
     { 
      handled = base.HandleResponseException(ex, request, requestUri, createWebRequest, getResponse, out response); 
     } 
     catch (WebServiceException webServiceException) 
     { 
      if(webServiceException.StatusCode > 0) 
       throw new HttpException(webServiceException.StatusCode, webServiceException.ErrorMessage); 
      throw; 
     } 
     return handled; 
    } 
의 내 재정에 다음과 같은 일을하고 있어요