2017-03-24 1 views
1

예기치 않은 예외가 발생하면 응답이 IExceptionHandler를 ovveride하면 DelegatingHandler에 도달하지 않습니다. 이 문제를 어떻게 해결할 수 있습니까?전역 예외 처리를 사용하면 위임됩니다. DelegatingHandler

webapi 2에서 요청 및 응답 메시지에 대해 감사 로거를 구현하려고합니다. 또한 전역 예외 처리기를 추가하려고합니다. 그러나 IExceptionHandler를 사용자 정의 구현으로 바꿀 때. 응답은 DelegatingHandler에 도달하지 않습니다. 예외적으로 - 따라서 응답에 대한 감사는 손실됩니다.

// add custom audittrail logger 
config.MessageHandlers.Add(new AuditLogHandler()); 
// replace global exception handeling 
config.Services.Replace(typeof(IExceptionHandler), new WebAPiExceptionHandler()); 

사용자 정의 예외 처리기

public class WebAPiExceptionHandler : ExceptionHandler 
{ 
    //A basic DTO to return back to the caller with data about the error 
    private class ErrorInformation 
    { 
     public string Message { get; set; } 
     public DateTime ErrorDate { get; set; } 
    } 

    public override void Handle(ExceptionHandlerContext context) 
    { 
     context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError, 
     new ErrorInformation { Message = "Iets is misgegaan", ErrorDate = DateTime.UtcNow })); 
    } 
} 

사용자 정의 Auditlogger

public class AuditLogHandler : DelegatingHandler 
{ 
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
     if (request.Content != null) 
     { 
      var task = await request.Content.ReadAsStringAsync(); 

      // .. code for loggign request 
     } 

     var result = await base.SendAsync(request, cancellationToken); 

     // .. code for logging response 
     // when I do not replace WebAPiExceptionHandler, code is reachred here 
     // When I Do use WebAPiExceptionHandler, code is not reached here 

     return result; 
    } 
} 

코드 webapi에 예외를 던지는에 대한

public class Values_v2Controller : ApiController 
{ 
    public string Get(int id) 
    { 
     throw new Exception("haha"); 
    } 
} 
WebApiConfig

에서

답변

1

망가 문제는 ExceptionHandler는 거짓 Handle(ExceptionHandlerContext context) 방법 ShouldHandle(ExceptionHandlerContext context) 경우 수익을 실행하는 것입니다 IExceptionHandler

public class WebAPiExceptionHandler : IExceptionHandler 
{ 
    public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken) 
    { 
     var fout = new ErrorInformation 
     { 
      Message = "Iets is misgegaan" 
      , ErrorDate = DateTime.UtcNow 
     }; 

     var httpResponse = context.Request.CreateResponse(HttpStatusCode.InternalServerError, fout); 

     context.Result = new ResponseMessageResult(httpResponse); 

     return Task.FromResult(0); 
    } 

    private class ErrorInformation 
    { 
     public string Message { get; set; } 
     public DateTime ErrorDate { get; set; } 
    } 
} 
+0

왜 이것이 효과가 있는지 설명 할 수 있습니까? –

0

인터페이스를 구현, 기본 클래스로 ExceptionHandler를 사용합니다.

항상 bool ShouldHandle(ExceptionHandlerContext context)을 무시하면 문제가 해결됩니다.

관련 문제