2014-03-04 1 views
1

웹 API에서 IExceptionhandler의 장점과 단점을 말해 줄 수 있습니까? 웹 API에서 예외를 처리하는 가장 좋은 방법은 무엇입니까?IExceptionhandler의 장점과 단점을 말씀해 주시겠습니까?

내 아래 예제에서는 IExceptionHandler를 사용하여 모든 웹 API 예외를 처리하고 있습니다. HandleCore 메서드에서 Httpexceptions, MyCustomerrormessages, 처리되지 않은 예외를 처리하고 있습니다. IExceptionHandler의 HandleCore 메서드 내에서 모든 예외를 처리하는 것이 올바른 방법인가요?

네임 스페이스 AccessServices.EntityModel {

/// <summary> 
/// To Handle the unhandled exceptions caught by Web API. 
/// </summary> 
public class CustomExceptionHandler : IExceptionHandler 
{ 
    public virtual Task HandleAsync(ExceptionHandlerContext context, 
            CancellationToken cancellationToken) 
    { 
     if (!ShouldHandle(context)) 
     { 
      return Task.FromResult(0); 
     } 

     return HandleAsyncCore(context, cancellationToken); 
    } 

    public virtual Task HandleAsyncCore(ExceptionHandlerContext context, 
             CancellationToken cancellationToken) 
    { 
     HandleCore(context); 
     return Task.FromResult(0); 
    } 

    public virtual void HandleCore(ExceptionHandlerContext context) 
    { 
    } 

    public virtual bool ShouldHandle(ExceptionHandlerContext context) 
    { 
     return context.ExceptionContext.CatchBlock.IsTopLevel; 
    } 

} 

/// <summary> 
///Response to unhandled exceptions caught by Web API. 
/// </summary> 
public class OopsExceptionHandler : CustomExceptionHandler 
{ 
    public override void HandleCore(ExceptionHandlerContext context) 
    { 
     var exception = context.Exception; 

     if (exception is HttpException) 
      { 
      var httpException = (HttpException)exception; 
       context.Result = new TextPlainErrorResult 
       { 
        Request = context.ExceptionContext.Request, 
        Content = exception.Message, 
        Statuscode=(HttpStatusCode)httpException.GetHttpCode() 
       }; 

      } 
     else if (exception is MyCustomException) 
     { 

     context.Result = new TextPlainErrorResult 
      { 
       //Request = context.ExceptionContext.Request, 
       Content = MyCustomException.Message, 
       Statuscode = MyCustomException.StatusCode 
      }; 

     } 

      else 
      { 
      context.Result = new TextPlainErrorResult 
            { 
             Request = context.ExceptionContext.Request, 
             Content = "Oops! Sorry! Something went wrong." + 
               "Please contact Administrator", 
             Statuscode=HttpStatusCode.InternalServerError 
            }; 
      } 
    } 
    /// <summary> 
    /// Sends HttpResponseMessage to the client 
    /// </summary> 
    private class TextPlainErrorResult : IHttpActionResult 
    { 
     public HttpRequestMessage Request { get; set; } 
     public string Content { get; set; } 
     public HttpStatusCode Statuscode { get; set; } 

     public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) 
     { 
      var response = new HttpResponseMessage(Statuscode) 

           { 
            Content = new StringContent(Content), 
            RequestMessage = Request 
           }; 
      return Task.FromResult(response); 
     } 
    } 
} 

}

답변

2

IExceptionHandler 의도는 웹 API에서 발생하는 처리되지 않은 예외에 대한 글로벌 오류 처리 메커니즘을 제공하는 것입니다.

ExceptionFilterAttributes는 인증 필터, 인증 필터, 동작 필터 & 동작에서 예외가 발생하는 경우와 같이 웹 API의 특정 영역에서만 예외를 처리 할 수 ​​있습니다.

예를 들어, MessageHandlers, 라우트 일치 또는 응답을 작성할 때 예외가 발생하면 예외 필터는 계층화 된 스택에있을 때 호출되므로 호출되지 않습니다. 따라서 전역 오류 처리 기능 (IExceptionLoggerIExceptionHandler)은 모든 계층에서 일관된 환경을 제공하려고합니다.

+0

1.IF IExceptionHandler에 단점이 있습니까? 2.Shall 난 내 웹 API에 혼자 또는 둘 다 IExceptionhandler를 사용합니까? – user3331492

+0

잘 모르겠습니다 ... 오래된 시스템에 비해 개선 된 점 .. –

+0

@ user3331492 : 두 번째 질문에 명확하지 않습니다. 더 자세히 설명해 주시겠습니까? –