8
ExceptionFilterAttribute에서 처리 된 것과 같은 예외를 표시하는 방법이 ASP.NET 웹 API에 있습니까?웹 API ExceptionFilterAttribute에서 예외 설정 처리
예외 필터를 사용하여 메서드 수준에서 예외를 처리하고 전역 적으로 등록 된 예외 필터로 전파를 중지하려고합니다. 컨트롤러 액션에 사용
필터 :
public class MethodExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is NotImplementedException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(context.Exception.Message)
};
// here in MVC you could set context.ExceptionHandled = true;
}
}
}
전역 적으로 등록 된 필터 :
public class GlobalExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is SomeOtherException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.SomethingElse)
{
Content = new StringContent(context.Exception.Message)
};
}
}
}
"예외 필터를 사용하여 메서드 수준에서 예외 처리"샘플을 제공해 주실 수 있습니까? – giacomelli
글로벌 필터를 얻으려면 먼저 생각했던 방법으로 예외를 처리해야합니다. 그래서'try/catch' 블록에 안전하지 않은 코드를 감싸고 처리하지 않으시겠습니까? –
예제가 추가되었습니다. – adamwtiko