웹 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);
}
}
}
}
1.IF IExceptionHandler에 단점이 있습니까? 2.Shall 난 내 웹 API에 혼자 또는 둘 다 IExceptionhandler를 사용합니까? – user3331492
잘 모르겠습니다 ... 오래된 시스템에 비해 개선 된 점 .. –
@ user3331492 : 두 번째 질문에 명확하지 않습니다. 더 자세히 설명해 주시겠습니까? –