0

I have a custom Gateway Filter Factory to check the request is valid or throw an exception, and I have an ErrorWebExceptionHandler to handle the exception.

I have already read Forbid Unauthenticated requests in Spring Cloud Gateway, and I tried in my ErrorWebExceptionHandler :

            // error body is some Object
            exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
            exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
            String errorBodyStr = objectMapper.writeValueAsString(errorBody);
            byte[] bytes = errorBodyStr.getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
            return exchange.getResponse().writeWith(Mono.just(buffer)).and(exchange.getResponse().setComplete());

status code and content type works well, but response body is empty.

leon remi
  • 3
  • 1

1 Answers1

0

i dont know why,but the source code has provided a graceful way。 you can override DefaultErrorWebExceptionHandler and DefaultErrorAttributes,and write your custom ErrorAttributes.i hava tested that it works!

see:

org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler#handle

Add: All GlobalFilters will be adapted into OrderedGatewayFilters.

pigman
  • 86
  • 7
  • thanks for your helping. I tried using the way as AbstractErrorWebExceptionHandler did, it can modify the response header and body, but it didn't prevent the request route to the downstream server. Is the method of throwing exception in GatewayFilter wrong? – leon remi Oct 27 '20 at 09:19
  • Try to define an ordered GlobalFilter ,which runs before the RouteToRequestUrlFilter , rather ran a GatewayFilter. – pigman Oct 28 '20 at 10:44
  • I made this GatewayFilter order(-100), it works! Thank you, could you edit the answer so that I can accept it? – leon remi Oct 29 '20 at 07:06