Spring Cloud Gateway (2) Exception Handle

ljft183·2022년 12월 12일
0

Spring_Cloud_Gateway

목록 보기
2/3

apply

	@Override
    public GatewayFilter apply(Config config) {
        return ((exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpResponse response = exchange.getResponse();

			// error 예외 처리 시 ex) 400 error
            if (false) {
                return handleException(exchange, HttpStatus.BAD_REQUEST); 
            }

            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                log.info("success");
            }));
        });
    }

Exception Handler

	private Mono<Void> handleException(ServerWebExchange exchange, HttpStatus status) {
        ServerHttpResponse response = exchange.getResponse();

        StringBuffer apiResult = null;
        byte [] bytes = null;

		/*
        bytes 값을 추가하여 body 부분에 값을 추가할 수 있음
		*/

        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);

        // response header 수정
        response.setStatusCode(status);
        // header 강제 주입
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, String.valueOf(MediaType.APPLICATION_JSON));
        

		log.info("error");
        return response.writeWith(Mono.just(dataBuffer));
    }

0개의 댓글