본문 바로가기
프로그래밍/SPRING BOOT

Zuul Exception customize - ERROR 처리하기

by 애플 로그 2022. 7. 18.
반응형

Zuul Exception customize - ERROR 처리하기

Zuul에서 예외 상황을 만들고 에러를 던졌더니, 아래와 같이만 나온다. 

Zuul Error Filter를 활용해서 원하는 방식으로 리턴 값을 만들어 보자

 

{
    "timestamp": "2022-07-17T23:16:07.563+00:00",
    "status": 500,
    "error": "Internal Server Error"
}

 

1. Zuul  sendErrorFilter를 비활성화

먼저 자동으로 구성된 sendErrorFilter를 비활성화 한다.

application.yml에 설정하면 된다.

zuul:
  SendErrorFilter:
    post:
      disable: true

 

2.  ErrorFilter 를 생성하자

ZuulFilter를 상속 받는다. 

public class ErrorFilter extends ZuulFilter {
}

 

메서드중의 일부가 재정의가 필요하다.

filterType() 메서드는  "error" 로 반환 한다.

@Override
public String filterType() {
    return "error";
}

 

filterOder()를 재정의 하고 -1 로 우선순위를 첫번째 필터가 되도록 한다.

@Override
public int filterOrder() {
    return -1;
}

모든 경우에 해당 필터를 이용하길 원하므로 shouldFilter() 메서드를 true로 설정한다.

@Override
public boolean shouldFilter() {
    return true;
}

 

마지막으로 run 메서드를 정의하면 된다.

    @Override
    public Object run()  {

        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        Throwable throwable = context.getThrowable();

        if (throwable instanceof ZuulException) {
            if (throwable.getCause() instanceof NotAllowedApiException) {
                log.error("Not Allowed Api - " + request.getRequestURI());
                context.remove("throwable");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("error", true);
                jsonObject.put("message", "Not Allowed Api");
                jsonObject.put("detailMessage", "Not Allowed Api - " + request.getRequestURI());

                context.setResponseBody(jsonObject.toJSONString());
                context.getResponse().setContentType("application/json");
                context.setResponseStatusCode(406);  // 406 Not Acceptable
            }
        }
        return null;
    }

RequestContext 인스턴스를 얻고 다음으로 throwable이 ZuulException 인스턴스 인지 확인한다.

 

새로이 개발한 Exception으로 조건별로 예외 처리를 하고 싶은 경우 NotAlloedApiException은 새로 생성하고,

예외처리하고 싶은 조건에서 아래와 같이 예외를 발생시키면 된다.

throw new NotAllowedApiException("Not Allowed Api");

 

context.remove("throwable") 을 통해서 후속 필터에서 추가로 발생하는 오류처리를 방지한다.

 

 

3. 후속필터에서 처리 할수 있도록 사용자 지정예외를 설정할수도 있다.

2번처럼 완전히 커스텀한 reponse결과가 아닌

reponse의 status code 정도만 수정하고 싶은경우에 사용하면 될것으로 생각된다.

if (throwable.getCause().getCause().getCause() instanceof ConnectException) {
    ZuulException customException = new ZuulException("", 503, "Service Unavailable");
    context.setThrowable(customException);
}

 

위를 통해  "error" type Filter에서 원하는 형식의 응답코드와 응답결과를 만들어 리턴하였다.

 

Zuul 관련 정리

 

[프로그래밍/SPRING] - Zuul API GATEWAY - 초간단 설정

 

Zuul API GATEWAY - 초간단 설정

Zuul API GATEWAY - 초간단 설정 Zuul이 뭐야? Zuul은 Netflix에서 개발한 Gateway 오픈 라이브러리 이다. Gateway 는 뭐야? zuul lib를 이용하여 Gateway 서버를 만들수 있다. ( proxy 서버라고 표현하기도..

www.appletong.com

 

[프로그래밍/SPRING BOOT] - Spring boot - HandlerInterceptorAdapter와 zuul Filter 의 사용시 문제

 

Spring boot - HandlerInterceptorAdapter와 zuul Filter 의 사용시 문제

Spring boot - HandlerInterceptorAdapter와 zuul Filter 의 사용시 문제 [문제 발생 내용] Spring boot application에서 HandlerInterceptorAdapter에 들어오는 사용자의 IP를 체크하는 Interceptor를 넣어서..

www.appletong.com

 

댓글